0% found this document useful (0 votes)
11 views

php2

php topics

Uploaded by

shawntel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

php2

php topics

Uploaded by

shawntel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

PHP Arrays

Arrays in PHP are a type of data structure that allows us to store multiple elements of similar or
different data types under a single variable thereby saving us the effort of creating a different
variable for every data. The arrays are helpful to create a list of elements of similar types,
which can be accessed using their index or key.
Suppose we want to store five names and print them accordingly. This can be easily done by
the use of five different string variables. But if instead of five, the number rises to a hundred,
then it would be really difficult for the user or developer to create so many different variables.
Here array comes into play and helps us to store every element within a single variable and
also allows easy access using an index or a key. An array is created using an array() function in
PHP.

Types of Array in PHP


Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value can
be assigned a specific key.
Multidimensional Arrays: An array that contains a single or multiple arrays within it and can be
accessed via multiple indices.

Indexed or Numeric Arrays


These type of arrays can be used to store any type of element, but an index is always a
number. By default, the index starts at zero. These arrays can be created in two different ways.
Examples of Indexed or Numeric Arrays
Example 1:
PHP

<?php

// One way to create an indexed array

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly

echo "Accessing the 1st array elements directly:\n";

echo $name_one[2], "\n";

echo $name_one[0], "\n";

echo $name_one[4], "\n";


// Second way to create an indexed array

$name_two[0] = "ZACK";

$name_two[1] = "ANTHONY";

$name_two[2] = "RAM";

$name_two[3] = "SALIM";

$name_two[4] = "RAGHAV";

// Accessing the elements directly

echo "Accessing the 2nd array elements directly:\n";

echo $name_two[2], "\n";

echo $name_two[0], "\n";

echo $name_two[4], "\n";

?>

Output:
Accessing the 1st array elements directly:

Ram

Zack

Raghav

Accessing the 2nd array elements directly:

RAM

ZACK

RAGHAV

Example 2: We can traverse an indexed array using loops in PHP.


PHP

<?php

// Creating an indexed array


$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// One way of Looping through an array using foreach

echo "Looping using foreach: \n";

foreach ($name_one as $val){

echo $val. "\n";

// count() function is used to count

// the number of elements in an array

$round = count($name_one);

echo "\nThe number of elements are $round \n";

// Another way to loop through the array using for

echo "Looping using for: \n";

for($n = 0; $n < $round; $n++){

echo $name_one[$n], "\n";

?>

Output:
Looping using foreach:

Zack

Anthony

Ram

Salim

Raghav

The number of elements is 5

Looping using for:

ZACK

ANTHONY

RAM
SALIM

RAGHAV

Traversing: We can loop through the indexed array in two ways. First by using for loop and
secondly by using foreach. You can refer to PHP Loops for the syntax and basic use.

Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every
value can be assigned with a user-defined key of string type.
Examples of Associative Arrays
Example 1:
PHP

<?php

// One way to create an associative array

$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",

"Ram"=>"Rani", "Salim"=>"Sara",

"Raghav"=>"Ravina");

// Second way to create an associative array

$name_two["zack"] = "zara";

$name_two["anthony"] = "any";

$name_two["ram"] = "rani";

$name_two["salim"] = "sara";

$name_two["raghav"] = "ravina";

// Accessing the elements directly

echo "Accessing the elements directly:\n";

echo $name_two["zack"], "\n";

echo $name_two["salim"], "\n";

echo $name_two["anthony"], "\n";

echo $name_one["Ram"], "\n";

echo $name_one["Raghav"], "\n";


?>

Output:
Accessing the elements directly:

zara

sara

any

Rani

Ravina

Example 2: We can traverse associative arrays in a similar way did in numeric arrays using
loops.
PHP

<?php

// Creating an Associative Array

$name_one = [

"Zack" => "Zara",

"Anthony" => "Any",

"Ram" => "Rani",

"Salim" => "Sara",

"Raghav" => "Ravina",

];

// Looping through an array using foreach

echo "Looping using foreach: \n";

foreach ($name_one as $val => $val_value) {

echo "Husband is " . $val . " and Wife is " . $val_value . "\n";

// Looping through an array using for


echo "\nLooping using for: \n";

$keys = array_keys($name_one);

$round = count($name_one);

for ($i = 0; $i < $round; ++$i) {

echo $keys[$i] . " " . $name_one[$keys[$i]] . "\n";

?>

Output:
Looping using foreach:

Husband is Zack and Wife is Zara

Husband is Anthony and Wife is Any

Husband is Ram and Wife is Rani

Husband is Salim and Wife is Sara

Husband is Raghav and Wife is Ravina

Looping using for:

zack zara

anthony any

ram rani

salim sara

raghav ravina

Traversing Associative Arrays: We can loop through the associative array in two ways. First by
using for loop and secondly by using foreach. You can refer to PHP Loops for the syntax and
basic use.

Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a
single element. In other words, we can define multi-dimensional arrays as an array of arrays. As
the name suggests, every element in this array can be an array and they can also hold other
sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using
multiple dimensions.
Examples of Multidimensional Arrays
Example 1:
PHP

<?php

// Defining a multidimensional array

$favorites = array(

array(

"name" => "Dave Punk",

"mob" => "5689741523",

"email" => "[email protected]",

),

array(

"name" => "Monty Smith",

"mob" => "2584369721",

"email" => "[email protected]",

),

array(

"name" => "John Flinch",

"mob" => "9875147536",

"email" => "[email protected]",

);

// Accessing elements

echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";

echo "John Flinch mobile number is: " . $favorites[2]["mob"];

?>

Output:
Dave Punk email-id is: [email protected]

John Flinch mobile number is: 9875147536


Example 2: We can traverse through the multidimensional array using for and foreach loop in
a nested way.
PHP

<?php

// Defining a multidimensional array

$favorites = array(

"Dave Punk" => array(

"mob" => "5689741523",

"email" => "[email protected]",

),

"Dave Punk" => array(

"mob" => "2584369721",

"email" => "[email protected]",

),

"John Flinch" => array(

"mob" => "9875147536",

"email" => "[email protected]",

);

// Using for and foreach in nested form

$keys = array_keys($favorites);

for($i = 0; $i < count($favorites); $i++) {

echo $keys[$i] . "\n";

foreach($favorites[$keys[$i]] as $key => $value) {

echo $key . " : " . $value . "\n";

echo "\n";

?>

Output:
Dave Punk
mob : 2584369721

email : [email protected]

John Flinch

mob : 9875147536

email : [email protected]

Traversing Multidimensional Arrays: That is, one for loop for the outer array and one for loop
for the inner array.
PHP is a server-side scripting language designed specifically for web development.

Multidimensional arrays in PHP


Multi-dimensional arrays in PHP are arrays that store other arrays as their elements. Each
dimension adds complexity, requiring multiple indices to access elements. Common forms
include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing
complex, structured data.
Dimensions
Dimensions of multidimensional array indicates the number of indices needed to select an
element. For a two dimensional array two indices to select an element.
Two dimensional array
It is the simplest form of a multidimensional array. It can be created using nested array. These
type of arrays can be used to store any type of elements, but the index is always a number. By
default, the index starts with zero.
Syntax:
array (

array (elements...),

array (elements...),

...

)
Example: In this example we creates a two-dimensional array containing names and locations.
The print_r() function is used to display the structure and contents of the array, showing the
nested arrays and their values.
php
<?php

// PHP program to create

// multidimensional array

// Creating multidimensional

// array

$myarray = array(

// Default key for each will

// start from 0

array("Ankit", "Ram", "Shyam"),

array("Unnao", "Trichy", "Kanpur")

);

// Display the array information

print_r($myarray);

?>

Output
Array

[0] => Array

[0] => Ankit

[1] => Ram

[2] => Shyam

)
[1] => Array

[0] => Unnao

[1] => Trichy

[2] => Kanpur

Two dimensional associative array


Al associative array is similar to indexed array but instead of linear storage (indexed storage),
every value can be assigned with a user-defined key of string type.
Example: In this example we creates a two-dimensional associative array to store students’
marks for various subjects. The print_r() function displays the array, showing each student’s
name as a key with subject-marks pairs.
php
<?php

// PHP program to creating two

// dimensional associative array

$marks = array(

// Ankit will act as key

"Ankit" => array(

// Subject and marks are

// the key value pair

"C" => 95,

"DCO" => 85,

"FOL" => 74,

),

// Ram will act as key

"Ram" => array(


// Subject and marks are

// the key value pair

"C" => 78,

"DCO" => 98,

"FOL" => 46,

),

// Anoop will act as key

"Anoop" => array(

// Subject and marks are

// the key value pair

"C" => 88,

"DCO" => 46,

"FOL" => 99,

),

);

echo "Display Marks: \n";

print_r($marks);

?>

Output
Display Marks:

Array

[Ankit] => Array

[C] => 95

[DCO] => 85

[FOL] => 74
)

[Ram] => Array

[C] => 78

[DCO] => 98

[FOL] => 46

[Anoop] => Array

[C] => 88

[DCO] => 46

[FOL] => 99

Three Dimensional Array


It is the form of multidimensional array. Initialization in Three-Dimensional array is same as
that of Two-dimensional arrays. The difference is as the number of dimension increases so the
number of nested braces will also increase.
Syntax:
array (

array (

array (elements...),

array (elements...),

...

),

array (

array (elements...),

array (elements...),

...
),

...

Example: In this example we creates a three-dimensional array with nested arrays containing
numeric values. The print_r() function is used to display the structure and contents of the
entire array.
php
<?php

// PHP program to creating three

// dimensional array

// Create three nested array

$myarray = array(

array(

array(1, 2),

array(3, 4),

),

array(

array(5, 6),

array(7, 8),

),

);
// Display the array information

print_r($myarray);

?>

Output
Array

[0] => Array

[0] => Array

[0] => 1

[1] => 2

[1] => Array

[0] => 3

[1] => 4

[1] => Array

[0] => Array

[0] => 5

[1] => 6

)
[1] => Array

[0] => 7

[1] => 8

Accessing multidimensional array elements


There are mainly two ways to access multidimensional array elements in PHP.
Elements can be accessed using dimensions as array_name[‘first dimension’][‘second
dimension’].
Elements can be accessed using for loop.
Elements can be accessed using for each loop.
Example: In this example we creates a multi-dimensional associative array to store students’
marks by subject. It displays specific marks and iterates through the array using a foreach loop
to print values.
php
<?php

// PHP code to create

// multidimensional array

// Creating multidimensional

// associative array

$marks = array(

// Ankit will act as key

"Ankit" => array(

// Subject and marks are


// the key value pair

"C" => 95,

"DCO" => 85,

"FOL" => 74,

),

// Ram will act as key

"Ram" => array(

// Subject and marks are

// the key value pair

"C" => 78,

"DCO" => 98,

"FOL" => 46,

),

// Anoop will act as key

"Anoop" => array(

// Subject and marks are

// the key value pair

"C" => 88,

"DCO" => 46,

"FOL" => 99,

),

);

// Accessing the array element

// using dimensions

// It will display the marks of

// Ankit in C subject

echo $marks['Ankit']['C'] . "\n";


// Accessing array elements using for each loop

foreach($marks as $mark) {

echo $mark['C']. " ".$mark['DCO']." ".$mark['FOL']."\n";

?>

Output
95

95 85 74

78 98 46

88 46 99

Sorting Arrays in PHP


Sorting arrays is one of the most common operation in programming, and PHP provides a
several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys,
in ascending or descending order. PHP also allows you to create custom sorting functions.

Sort an Array in Ascending Order – sort() Function


The sort() function is used to sort an array by values in ascending order. It reindexes the array
numerically after sorting the array elements. It means the original keys are lost.
Syntax:
sort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array elements in ascending order using PHP sort() function.
PHP
<?php

$arr = array(40, 61, 2, 22, 13);

sort($arr);

print_r($arr);

?>
Output
Array

[0] => 2

[1] => 13

[2] => 22

[3] => 40

[4] => 61

Sort an Array in Descending Order – rsort() Function


The rsort() function sorts an array by values in descending order. Like sort(), it reindexes the
array numerically.
Syntax:
rsort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array elements in descending order using PHP rsort() function.
PHP
<?php

$arr = array(40, 61, 2, 22, 13);

rsort($arr);

print_r($arr);

?>

Output
Array

[0] => 61

[1] => 40

[2] => 22
[3] => 13

[4] => 2

Sort an Array in Ascending Order According to Array Values – asort()


Function
The asort() function sorts an array by values in ascending order while maintaining the key-value
association.
Syntax:
asort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array in ascending order according to array values using PHP rsort() function.
PHP
<?php

$arr = array(

"Ayush"=>"23",

"Shankar"=>"47",

"Kailash"=>"41"

);

asort($arr);

print_r($arr)

?>

Output
Array

[Ayush] => 23

[Kailash] => 41

[Shankar] => 47

)
Sort an Array in Descending Order According to Array Value – arsort()
Function
The arsort() function sorts an array by values in descending order while maintaining the key-
value association.
Syntax:
arsort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array in descending order according to array values using PHP arsort()
function.
PHP
<?php

$arr = array(

"Ayush"=>"23",

"Shankar"=>"47",

"Kailash"=>"41"

);

arsort($arr);

print_r($arr);

?>

Output
Array

[Shankar] => 47

[Kailash] => 41

[Ayush] => 23

Sort an Array in Ascending Order According to Array Key – ksort()


Function
The ksort() function sorts an array by keys in ascending order, preserving key-value pairs.
Syntax:
ksort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array in ascending order according to array ket using PHP ksort() function.
PHP
<?php

$arr = array(

"Ayush"=>"23",

"Shankar"=>"47",

"Kailash"=>"41"

);

ksort($arr);

print_r($arr)

?>

Output
Array

[Ayush] => 23

[Kailash] => 41

[Shankar] => 47

Sort Array in Descending Order According to Array Key – krsort()


Function
The krsort() function sorts an array by keys in descending order, preserving key-value pairs.
Syntax:
krsort(array &$array, int $sort_flags = SORT_REGULAR);

Example: Sort the array in descending order according to array ket using PHP krsort() function.
PHP
<?php

$arr = array(

"Ayush"=>"23",

"Shankar"=>"47",

"Kailash"=>"41"

);

krsort($arr);

print_r($arr)

?>

Output
Array

[Shankar] => 47

[Kailash] => 41

[Ayush] => 23

Sort an Array using User-Defined Comparison Function – uasort()


Function
The uasort() function sorts an array with a user-defined comparison function, while
maintaining the key-value association.
Syntax:
uasort(array &$array, callable $callback);

Example: Sort an array using comparison function (user defined) in uasort() function.
PHP
<?php

// User defined comparator function

function sort_array($a, $b) {


if ($a==$b) return 0;

return ($a<$b)?-1:1;

// Input Array

$arr = array(

"a" => 4,

"b" => 2,

"g" => 8,

"d" => 6,

"e" => 1,

"f" => 9

);

uasort($arr,"sort_array");

// Print the sorted array

print_r($arr);

?>

Output
Array

[e] => 1

[b] => 2

[a] => 4

[d] => 6

[g] => 8

[f] => 9

)
PHP | Superglobals
We already have discussed about variables and global variables in PHP in the post PHP |
Variables and Data Types . In this article, we will learn about superglobals in PHP.
These are specially-defined array variables in PHP that make it easy for you to get
information about a request or its context. The superglobals are available throughout your
script. These variables can be accessed from any function, class or any file without doing any
special task such as declaring any global variable etc. They are mainly used to store and get
information from one page to another etc in an application.
Below is the list of superglobal variables available in PHP:
$GLOBALS
$_SERVER
$_REQUEST
$_GET
$_POST
$_SESSION
$_COOKIE
$_FILES
$_ENV
Let us now learn about some of these superglobals in detail:
$GLOBALS : It is a superglobal variable which is used to access global variables from
anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[] where
index holds the global variable name, which can be accessed.
Below program illustrates the use of $GLOBALS in PHP:
PHP

<?php

$x = 300;

$y = 200;

function multiplication(){

$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];


}

multiplication();

echo $z;

?>

Output :
60000

In the above code two global variables are declared $x and $y which are assigned some value
to them. Then a function multiplication() is defined to multiply the values of $x and $y and
store in another variable $z defined in the GLOBAL array.
$_SERVER : It is a PHP super global variable that stores the information about headers, paths
and script locations. Some of these elements are used to get the information from the
superglobal variable $_SERVER.
Below program illustrates the use of $_SERVER in PHP:

PHP

<?php

echo $_SERVER['PHP_SELF'];

echo "<br>";

echo $_SERVER['SERVER_NAME'];

echo "<br>";

echo $_SERVER['HTTP_HOST'];

echo "<br>";

echo $_SERVER['HTTP_USER_AGENT'];

echo "<br>";

echo $_SERVER['SCRIPT_NAME'];

echo "<br>"

?>

Output :
In the above code we used the $_SERVER elements to get some information. We get the
current file name which is worked on using ‘PHP_SELF’ element. Then we get server name
used currently using ‘SERVER_NAME’ element. And then we get the host name through
‘HTTP_HOST’.
$_REQUEST : It is a superglobal variable which is used to collect the data after submitting a
HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same
task and are widely used.
Below is the HTML and PHP code to explain how $_REQUEST works:
HTML

<!DOCTYPE html>

<html>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

NAME: <input type="text" name="fname">

<button type="submit">SUBMIT</button>

</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = htmlspecialchars($_REQUEST['fname']);

if(empty($name)){

echo "Name is empty";

} else {

echo $name;

?>

</body>

</html>
Output :

In the above code we have created a form that takes the name as input from the user and
prints it’s name on clicking of submit button. We transport the data accepted in the form to
the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute,
because we manipulate the data in the same page using the PHP code. The data is retrieved
using the $_REQUEST superglobal array variable
$_POST : It is a super global variable used to collect data from the HTML form after
submitting it. When form uses method post to transfer data, the data is not visible in the
query string, because of which security levels are maintained in this method.
Below is the HTML and PHP code to explain how $_POST works:
HTML

<!DOCTYPE html>

<html>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

<label for="name">Please enter your name: </label>

<input name="name" type="text"><br>

<label for="age">Please enter your age: </label>

<input name="age" type="text"><br>

<input type="submit" value="Submit">

<button type="submit">SUBMIT</button>

</form>

<?php

$nm=$_POST['name'];

$age=$_POST['age'];

echo "<strong>".$nm." is $age years old.</strong>";

?>

</body>

</html>

Output :
In the above code we have created a form that takes name and age of the user and accesses
the data using $_POST super global variable when they submit the data. Since each
superglobal variable is an array it can store more than one values. Hence we retrieved name
and age from the $_POST variable and stored them in $nm and $age variables.
$_GET : $_GET is a super global variable used to collect data from the HTML form after
submitting it. When form uses method get to transfer data, the data is visible in the query
string, therefore the values are not hidden. $_GET super global array variable stores the
values that come in the URL.
Below is the HTML and PHP code to explain how $_GET works:
HTML

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body bgcolor="cyan">

<?php

$name = $_GET['name'];

$city = $_GET['city'];

echo "<h1>This is ".$name." of ".$city."</h1><br>";

?>

<img src = "2.jpg" alt = "nanilake" height = "400" width="500" />

</body>

</html>

We are actually seeing half of the logic just now. In the above code we have created a
hyperlink image of Nainital Lake which will take us to picture.php page and with it will also
take the parameters name=”Nainilake” and city=”Nainital”.
That is when we click on the small image of Nainital Lake we will be taken to the next page
picture.php along with the parameters. As the default method is get, these parameters will
be passed to the next page using get method and they will be visible in the address bar.
When we want to pass values to an address they are attached to the address using a question
mark (?).
Here the parameter name=Nainilake is attached to the address. If we want to add more
values, we can add them using ampersand (&) after every key-value pair similarly
as city=Nainital is added using ampersand after the name parameter. Now after clicking on
the image of Nainital Lake we want the picture.php page to be displayed with the value of
parameter displayed along with it.

HTTP GET and POST Methods in PHP


In this article, we will know what HTTP GET and POST methods are in PHP, how to implement
these HTTP methods & their usage, by understanding them through the examples.
HTTP: The Hypertext Transfer Protocol (HTTP) is designed to enable communications between
clients and servers. HTTP works as a request-response protocol between a client and server. A
web browser may be the client, and an application on a computer that hosts a website may be
the server. A client (browser) submits an HTTP request to the server; then the server returns a
response to the client. The response contains status information about the request and may
also contain the requested content.
There are 2 HTTP request methods:
GET: Requests data from a specified resource.
POST: Submits data to be processed to a specified resource.
We will understand both these methods in detail through the examples.
GET Method: In the GET method, the data is sent as URL parameters that are usually strings of
name and value pairs separated by ampersands (&). In general, a URL with GET data will look
like this:
Example: Consider the below example:
http://www.example.com/action.php?name=Sam&weight=55

Here, the bold parts in the URL denote the GET parameters and the italic parts denote the
value of those parameters. More than one parameter=value can be embedded in the URL by
concatenating with ampersands (&). One can only send simple text data via GET method.
Example: This example illustrates the HTTP GET method in PHP.
HTML

<?php

error_reporting(0);

if( $_GET["name"] || $_GET["weight"] )

{
echo "Welcome ". $_GET['name']. "<br />";

echo "You are ". $_GET['weight']. " kgs in weight.";

exit();

?>

<html>

<body>

<form action="<?php $_PHP_SELF ?>" method="GET">

Name: <input type="text" name="name" />

Weight:<input type="text" name="weight" />

<input type="submit" />

</form>

</body>

</html>

Output:

GET() method

Advantages:
Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the
page with specific query string values.
GET requests can be cached and GET requests to remain in the browser history.
GET requests can be bookmarked.
Disadvantages:
The GET method is not suitable for passing sensitive information such as the username and
password, because these are fully visible in the URL query string as well as potentially stored in
the client browser’s memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL
is limited. So, there is a limitation for the total data to be sent.
POST Method: In the POST method, the data is sent to the server as a package in a separate
communication with the processing script. Data sent through the POST method will not be
visible in the URL.
Example: Consider the below example:
POST /test/demo_form.php HTTP/1.1

Host: gfs.com

SAM=451&MAT=62

The query string (name/weight) is sent in the HTTP message body of a POST request.
Example: This example illustrates the HTTP POST method in PHP. Here, we have used
the preg_match() function to search string for a pattern, returns true if a pattern exists,
otherwise returns false.
HTML

<?php

error_reporting(0);

if( $_POST["name"] || $_POST["weight"] )

if (preg_match("/[^A-Za-z'-]/",$_POST['name'] ))

die ("invalid name and name should be alpha");

echo "Welcome ". $_POST['name']. "<br />";

echo "You are ". $_POST['weight']. " kgs in weight.";

exit();

?>

<html>

<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">

Name: <input type = "text" name = "name" />

Weight: <input type = "text" name = "weight" />

<input type = "submit" />

</form>

</body>
</html>

Output:

POST() method

Advantages:
It is more secure than GET because user-entered information is never visible in the URL query
string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text
data as well as binary data (uploading a file) using POST.
Disadvantages:
Since the data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with a specific query.
POST requests are never cached
POST requests do not remain in the browser history.

PHP | Regular Expressions


Regular expressions commonly known as a regex (regexes) are a sequence of characters
describing a special search pattern in the form of text string. They are basically used in
programming world algorithms for matching some loosely defined patterns to achieve some
relevant tasks. Some times regexes are understood as a mini programming language with a
pattern notation which allows the users to parse text strings. The exact sequence of characters
are unpredictable beforehand, so the regex helps in fetching the required strings based on a
pattern definition.
Regular Expression is a compact way of describing a string pattern that matches a particular
amount of text. As you know, PHP is an open-source language commonly used for website
creation, it provides regular expression functions as an important tool. Like PHP, many other
programming languages have their own implementation of regular expressions. This is the
same with other applications also, which have their own support of regexes having various
syntaxes. Many available modern languages and tools apply regexes on very large files and
strings. Let us look into some of the advantages and uses of regular expressions in our
applications.
Advantages and uses of Regular expressions:
In many scenarios, developers face problems whenever data are collected in free text fields as
most of the programming deals with data entries. Regular expressions are used almost
everywhere in today’s application programming.
Regular expressions help in validation of text strings which are of programmer’s interest.
It offers a powerful tool for analyzing, searching a pattern and modifying the text data.
It helps in searching specific string pattern and extracting matching results in a flexible manner.
It helps in parsing text files looking for a defined sequence of characters for further analysis or
data manipulation.
With the help of in-built regexes functions, easy and simple solutions are provided for
identifying patterns.
It effectively saves a lot of development time, which are in search of specific string pattern.
It helps in important user information validations like email address, phone numbers and IP
address.
It helps in highlighting special keywords in a file based on search result or input.
It helps in identifying specific template tags and replacing those data with the actual data as
per the requirement.
Regexes are very useful for creation of HTML template system recognizing tags.
Regexes are mostly used for browser detection, spam filtration, checking password strength
and form validations.
We cannot cover everything under this topic, but let us look into some of the major regular
expression concepts. The following table shows some regular expressions and the
corresponding string which matches the regular expression pattern.

Regular
Expression Matches

geeks The string “geeks”

^geeks The string which starts with “geeks”

geeks$ The string which have “geeks” at the end.


^geeks$ The string where “geeks” is alone on a string.

[abc] a, b, or c

[a-z] Any lowercase letter

[^A-Z] Any letter which is NOT a uppercase letter

(gif|png) Either “gif” or “png”

[a-z]+ One or more lowercase letters

^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter

([ax])([by]) ab, ay, xb, xy

[^A-Za-z0-9] Any symbol other than a letter or other than number

([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers

Note: Complex search patterns can be created by applying some basic regular expression rules.
Even many arithmetic operators like +, ^, – are used by regular expressions for creating little
complex patterns.
Operators in Regular Expression: Let us look into some of the operators in PHP regular
expressions.

Operato
r Description

^ It denotes the start of string.

$ It denotes the end of string.

. It denotes almost any single character.


() It denotes a group of expressions.

[] It finds a range of characters for example [xyz] means x, y or z .

[^] It finds the items which are not in range for example [^abc] means NOT a, b or c.

It finds for character range within the given item range for example [a-z] means a through
– (dash)
z.

| (pipe) It is the logical OR for example x | y means x OR y.

? It denotes zero or one of preceding character or item range.

* It denotes zero or more of preceding character or item range.

+ It denotes one or more of preceding character or item range.

{n} It denotes exactly n times of preceding character or item range for example n{2}.

{n, } It denotes atleast n times of preceding character or item range for example n{2, }.

{n, m} It denotes atleast n but not more than m times for example n{2, 4} means 2 to 4 of n.

\ It denotes the escape character.

Special Character Classes in Regular Expressions: Let us look into some of the special characters
used in regular expressions.

Special Character Meaning

\n It denotes a new line.

\r It denotes a carriage return.


\t It denotes a tab.

\v It denotes a vertical tab.

\f It denotes a form feed.

\xxx It denotes octal character xxx.

\xhh It denotes hex character hh.

Shorthand Character Sets: Let us look into some shorthand character sets available.

Shorthand Meaning

\s Matches space characters like space, newline or tab.

\d Matches any digit from 0 to 9.

Matches word characters including all lower and upper case letters, digits and
\w
underscore.

Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined
functions for regular expressions in PHP. PHP provides the programmers to many useful
functions to work with regular expressions.
The below listed in-built functions are case-sensitive.

Function Definition

This function searches for a specific pattern against some string. It returns true if
preg_match()
pattern exists and false otherwise.

preg_match_all( This function searches for all the occurrences of string pattern against the string.
) This function is very useful for search and replace.

This function searches for specific string pattern and replace the original string
ereg_replace()
with the replacement string, if found.
The function behaves like ereg_replace() provided the search for pattern is not
eregi_replace()
case sensitive.

This function behaves like ereg_replace() function provided the regular


preg_replace()
expressions can be used in the pattern and replacement strings.

The function behaves like the PHP split() function. It splits the string by regular
preg_split()
expressions as its parameters.

This function searches all elements which matches the regular expression pattern
preg_grep()
and returns the output array.

This function takes string and quotes in front of every character which matches
preg_quote()
the regular expression.

This function searches for a string which is specified by a pattern and returns true
ereg()
if found, otherwise returns false.

This function behaves like ereg() function provided the search is not case
eregi()
sensitive.

Note:
By default, regular expressions are case sensitive.
There is a difference between strings inside single quotes and strings inside double quotes in
PHP. The former are treated literally, whereas for the strings inside double-quotes means the
content of the variable is printed instead of just printing their names.
Example 1:

<?php

// Declare a regular expression

$regex = '/^[a-zA-Z ]*$/';

// Declare a string

$nameString = 'Sharukh khan';


// Use preg_match() function to

// search string pattern

if(preg_match($regex, $nameString)) {

echo("Name string matching with"

. " regular expression");

else {

echo("Only letters and white space"

. " allowed in name string");

?>

Output:
Name string matching with regular expression

Example 2:

<?php

// Declare a regular expression

$regex = "/<b>(.*)<\/b>/U";

// Declare a string

$inputString = "Name: <b>John</b> Position: <b>Developer</b>";

// Use preg_match_all() function to perform

// a global regular expression match

preg_match_all($regex, $inputString, $output);

echo $output[0][0]." <br> ".$output[0][1]."\n";

?>

Output:
John

Developer

Example 3:

<?php

// Declare a regular expression

$regex = "([0-9]+)";

// Declare a string

$original = "Completed graduation in 2004";

$replaceWith = "2002";

// Use ereg_replace() function to search a

// string pattern in an other string

$original = ereg_replace($regex, $replaceWith, $original);

// Display result

echo $original;

?>

Output:
Completed graduation in 2002

Example 4:

<?php

<?php

// Declare a string

$ip = "134.645.478.670";

// Declare a regular expression

$regex = "/\./";
// Use preg_split() function to

// convert a given string into

// an array

$output = preg_split ($regex, $ip);

echo "$output[0] <br>";

echo "$output[1] <br>";

echo "$output[2] <br>";

echo "$output[3] <br>";

?>

Output:
134

645

478

670

Metacharacters: There are two kinds of characters that are used in regular expressions these
are: Regular characters and Metacharacters. Regular characters are those characters which
have a ‘literal’ meaning and Metacharacters are those characters which have ‘special’ meaning
in regular expression.

Metacharacte Description Example


r
. It matches any single character other /./ matches string which has a single
than a new line. character.
^ It matches the beginning of string. /^geeks/ matches any string that starts with
geeks.
$ It matches the string pattern at the /com$/ matches string ending with com for
end of the string. example google.com etc.
* It matches zero or more characters. /com*/ matches commute, computer,
compromise etc.
+ It matches preceding character For example /z+oom/ matches zoom.
appear atleast once.
\ It is used to esacape metacharacters /google\.com/ will treat the dot as a literal
in regex. value, not metacharacter.
a-z It matches lower case letters. geeks
A-Z It matches upper case letters. GEEKS
0-9 It matches any number between 0 /0-5/ matches 0, 1, 2, 3, 4, 5
and 9.
[…] It matches character class. /[pqr]/ matches pqr
Other Examples:

Regular Meaning
expression
^[.-a-z0-9A-Z] It matches string with dot, dash and any lower case letters, numbers between 0 and
9 and upper case letters.
+@[a-z0-9A-Z] It matches string with @ symbol in the beginning followed by any lower case
letters, numbers between 0 and 9 and upper case letters.
+\.[a-z]{2, 6}$/ It escapes the dot and then matches string with any lower case letters with string
length between 2 and 6 at the end.
Note:
Metacharacters are very powerful in regular expressions pattern matching solutions. It handles
a lot of complex pattern processing.
Every character which is not a metacharacter is definitely a regular character.
Every regular character matches the same character by itself.
POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic expressions
which are called POSIX regular expressions. Some times, complex expression are created by
combining various elements or operators in regular expressions. The very basic regex is the one
which matches a single character.
Lets look into some of the POSIX regular expressions.

Regex Meaning
[0-9] It matches digit from 0 through 9.
[a-z] It matches any lowercase letter from a through z.
[A-Z] It matches any uppercase letter from A through Z.
[a-Z] It matches any lowercase letter a through uppercase letter Z.
[:lower:] It matches any lower case letters.
[:upper:] It matches any upper case letters.
[:alpha:] It matches all alphabetic characters or letters from a-z and A-Z.
[[:alpha:]] It matches any string containing alphabetic characters or letters.
[:alnum:] It matches all alphanumeric characters i.e all digits(0-9) and letters (a-z A-Z).
[[:alnum:]] It matches any string containing alphanumeric characters and digits.
[:digit:] It matches all the digits from 0 to 9.
[[:digit:]] It matches any string containing digits from 0 to 9.
[:xdigit:] It matches all the hexadecimal digits.
[:punct:] It matches all the punctuation symbols.
[:blank:] It matches blank characters like space and tab.
[:space:] It matches all whitespace characters like line breaks.
[[:space:]] It matches any string containing a space.
[:cntrl:] It matches all control characters.
[:graph:] It matches all visible or printed characters other than spaces and control characters.
[:print:] It matches all printed characters and spaces other than control characters.
[:word:] It matches all word characters like digits, letters and underscore.
Quantifiers in Regular Expression: Quantifiers are special characters which tell the quantity,
frequency or the number of instances or occurrence of bracketed character or group of
characters. They are also called as greedy and lazy expressions. Let us look into some of the
concepts and examples of quantifiers.

Quantifier Meaning
a+ It matches the string containing at least one a.
a* It matches the string containing zero or more a’s.
a? It matches any string containing zero or one a’s.
a{x} It matches letter ‘a’ exaclty x times .
a{2, 3} It matches any string containing the occurrence of two or three a’s.
a{2, } It matches any string containing the occurrence of at least two a’s.
a{2} It matches any string containing the occurrence of exactly two a’s.
a{, y} It matches any string containing the occurrence of not more than y number of a’s.
a$ It matches any string with ‘a’ at the end of it.
^a It matches any string with ‘a’ at the beginning of it.
[^a-zA-Z] It matches any string pattern not having characters from a to z and A to Z.
a.a It matches any string pattern containing a, then any character and then another a.
^.{3}$ It matches any string having exactly three characters.
Note:
The $ character inside the expression will match the end of the target string.
The *, ?, + symbols in a regular expression denotes the frequency of occurrence of a character.
If it occurs zero or more time, zero or one time and one or more times.
The ^ character inside the expression will match the beginning of the target string.
The . metacharacter matches any single character other than the newline.
Commonly known regular expression engines:
Regexp
RegexBuddy
Conclusion: A regular expression is a pattern that describes some string text in a particular
pattern or it is defined as a pattern-matching algorithm expressed in a single line. Regular
expressions are very useful in the programming world for validation checks and recognizing
specific templates. PHP provides many in-built functions supporting regular expressions.
Metacharacters helps in creating complex patterns.

PHP Form Processing


In this article, we will discuss how to process form in PHP. HTML forms are used to send the
user information to the server and returns the result back to the browser. For example, if you
want to get the details of visitors to your website, and send them good thoughts, you can
collect the user information by means of form processing. Then, the information can be
validated either at the client-side or on the server-side. The final result is sent to the client
through the respective web browser. To create a HTML form, form tag should be used.
Attributes of Form Tag:

Attribute Description
name or It specifies the name of the form and is used to identify individual forms.
id
action It specifies the location to which the form data has to be sent when the form is submitted.
method It specifies the HTTP method that is to be used when the form is submitted. The possible
values are get and post. If get method is used, the form data are visible to the users in the
url. Default HTTP method is get.
encType It specifies the encryption type for the form data when the form is submitted.
novalidate It implies the server not to verify the form data when the form is submitted.
Controls used in forms: Form processing contains a set of controls through which the client and
server can communicate and share information. The controls used in forms are:
Textbox: Textbox allows the user to provide single-line input, which can be used for getting
values such as names, search menu and etc.
Textarea: Textarea allows the user to provide multi-line input, which can be used for getting
values such as an address, message etc.
DropDown: Dropdown or combobox allows the user to provide select a value from a list of
values.
Radio Buttons: Radio buttons allow the user to select only one option from the given set of
options.
CheckBox: Checkbox allows the user to select multiple options from the set of given options.
Buttons: Buttons are the clickable controls that can be used to submit the form.
Creating a simple HTML Form: All the form controls given above is designed by using
the input tag based on the type attribute of the tag. In the below script, when the form is
submitted, no event handling mechanism is done. Event handling refers to the process done
while the form is submitted. These event handling mechanisms can be done by using javaScript
or PHP. However, JavaScript provides only client-side validation. Hence, we can use PHP for
form processing.
HTML Code:
<!DOCTYPE html>
<html>

<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>
</form>
</body>
</html>
Form Validation: Form validation is done to ensure that the user has provided the relevant
information. Basic validation can be done using HTML elements. For example, in the above
script, the email address text box is having a type value as “email”, which prevents the user
from entering the incorrect value for an email. Every form field in the above script is followed
by a required attribute, which will intimate the user not to leave any field empty before
submitting the form. PHP methods and arrays used in form processing are:
isset(): This function is used to determine whether the variable or a form control is having a
value or not.
$_GET[]: It is used the retrieve the information from the form control through the parameters
sent in the URL. It takes the attribute given in the url as the parameter.
$_POST[]: It is used the retrieve the information from the form control through the HTTP POST
method. IT takes name attribute of corresponding form control as the parameter.
$_REQUEST[]: It is used to retrieve an information while using a database.
Form Processing using PHP: Above HTML script is rewritten using the above mentioned
functions and array. The rewritten script validates all the form fields and if there are no errors,
it displays the received information in a tabular form.
Example:

<?php

if (isset($_POST['submit']))

if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||

(!isset($_POST['password'])) || (!isset($_POST['gender'])))

$error = "*" . "Please fill all the required fields";

else

$firstname = $_POST['firstname'];

$lastname = $_POST['lastname'];

$address = $_POST['address'];

$emailaddress = $_POST['emailaddress'];

$password = $_POST['password'];

$gender = $_POST['gender'];

?>

<html>

<head>

<title>Simple Form Processing</title>

</head>

<body>

<h1>Form Processing using PHP</h1>

<fieldset>

<form id="form1" method="post" action="form.php">

<?php

if (isset($_POST['submit']))

if (isset($error))

echo "<p style='color:red;'>"

. $error . "</p>";
}

?>

FirstName:

<input type="text" name="firstname"/>

<span style="color:red;">*</span>

<br>

<br>

Last Name:

<input type="text" name="lastname"/>

<span style="color:red;">*</span>

<br>

<br>

Address:

<input type="text" name="address"/>

<span style="color:red;">*</span>

<br>

<br>

Email:

<input type="email" name="emailaddress"/>

<span style="color:red;">*</span>

<br>

<br>

Password:

<input type="password" name="password"/>

<span style="color:red;">*</span>

<br>

<br>

Gender:

<input type="radio"

value="Male"

name="gender"> Male
<input type="radio"

value="Female"

name="gender">Female

<br>

<br>

<input type="submit" value="Submit" name="submit" />

</form>

</fieldset>

<?php

if(isset($_POST['submit']))

if(!isset($error))

echo"<h1>INPUT RECEIVED</h1><br>";

echo "<table border='1'>";

echo "<thead>";

echo "<th>Parameter</th>";

echo "<th>Value</th>";

echo "</thead>";

echo "<tr>";

echo "<td>First Name</td>";

echo "<td>".$firstname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Last Name</td>";

echo "<td>".$lastname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Address</td>";

echo "<td>".$address."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Email Address</td>";


echo "<td>" .$emailaddress."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Password</td>";

echo "<td>".$password."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Gender</td>";

echo "<td>".$gender."</td>";

echo "</tr>";

echo "</table>";

?>

</body>

</html>

Output:

Note: When the PHP and HTML are coded in a single file, the file should be saved as PHP. In the
form, the value for the action parameter should be a file name.

PHP Date and Time


In this article, we will see how to get the date & time using the date() & time() function in PHP,
we will also see the various formatting options available with these functions & understand
their implementation through the examples.
Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks.
Some of the predefined functions in PHP for date and time are discussed below.
PHP date() Function: The PHP date() function converts timestamp to a more readable date and
time format.
Why do we need the date() function?
The computer stores dates and times in a format called UNIX Timestamp, which measures time
as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time
on January 1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical format for
humans to read, PHP converts timestamp to a format that is readable and more
understandable to humans.
Syntax:
date(format, timestamp)

Explanation:
The format parameter in the date() function specifies the format of returned date and time.
The timestamp is an optional parameter, if it is not included then the current date and time will
be used.
Example: The below program explains the usage of the date() function in PHP.
PHP

<?php

echo "Today's date is :";

$today = date("d/m/Y");

echo $today;

?>

Output:
Today's date is :05/12/2017

Formatting options available in date() function: The format parameter of the date() function is
a string that can contain multiple characters allowing to generate the dates in various formats.
Date-related formatting characters that are commonly used in the format string:
d: Represents day of the month; two digits with leading zeros (01 or 31).
D: Represents day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents year in two digits (08 or 14).
Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
PHP

<?php

echo "Today's date in various formats:" . "\n";

echo date("d/m/Y") . "\n";

echo date("d-m-Y") . "\n";

echo date("d.m.Y") . "\n";

echo date("d.M.Y/D");

?>

Output:
Today's date in various formats:

05/12/2017

05-12-2017

05.12.2017

05.Dec.2017/Tue

The following characters can be used along with the date() function to format the time string:
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the date() function in PHP.
PHP
<?php

echo date("h:i:s") . "\n";

echo date("M,d,Y h:i:s A") . "\n";

echo date("h:i a");

?>

Output:
03:04:17

Dec,05,2017 03:04:17 PM

03:04 pm

PHP time() Function: The time() function is used to get the current time as a Unix timestamp
(the number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00
GMT).
The following characters can be used to format the time string:
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the time() function in PHP.
PHP

<?php

$timestamp = time();

echo($timestamp);

echo "\n";

echo(date("F d, Y h:i:s A", $timestamp));

?>

Output:
1512486297

December 05, 2017 03:04:57 PM


PHP mktime() Function: The mktime() function is used to create the timestamp for a specific
date and time. If no date and time are provided, the timestamp for the current date and time is
returned.
Syntax:
mktime(hour, minute, second, month, day, year)

Example: The below example explains the usage of the mktime() function in PHP.
PHP

<?php

echo mktime(23, 21, 50, 11, 25, 2017);

?>

Output:
1511652110

The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.

Describe PHP Include and Require


In this article, we will see what include() & the require() functions is, also will know how these
functions affect the execution of the code, their differences & usage in PHP, along with
understanding their implementation through the examples. As we know PHP allows us to
create various functions and various elements that are used multiple times in multiple pages.
Scripting the same function in multiple pages is a task of great effort and would consume lots
of time & also impact the execution of the code. This can be avoided if we follow and use the
concept of file inclusion which helps us to include various files including text or codes into a
single program which saves the effort of writing the full function or code multiple times. This
also provides another advantage. If we want to change any code then instead of editing it in all
the files, we just need to edit the source file and all codes will be automatically changed. There
are two functions that help us to include files:
PHP include() function
PHP require() function
We will understand both the function & their usage through the examples.
PHP include() function: This function is used to copy all the contents of a file called within the
function, text wise into a file from which it is called. This happens before the server executes
the code.
Example: This example is using the include() function in PHP.
even.php
<?php

// File to be included

echo "Hello GeeksforGeeks";

?>

Now, try to include this file into another PHP file index.php file, will see the contents of both
the file are shown.
index.php

<?php

include("even.php");

echo "<br>Above File is Included"

?>

Output:

Demo of include() function

PHP require() function: The require() function performs same as the include() function. It also
takes the file that is required and copies the whole code into the file from where the require()
function is called.
Example: This example is using the require() function in PHP.
even.php

<?php

// File to be included

echo "Hello GeeksforGeeks";

?>

Now, if we try to include this file using require() function this file into a web page we need to
use a index.php file. We will see that the contents of both files are shown.
index.php

<?php

require("even.php");
echo "<br>Above File is Required"

?>

Output:

Demo of require() function

Difference between include() function vs require() function: Both functions act as same and
produce the same results, but if by any chance a fatal error arises, then the difference comes
to the surface, which we will see following this example. Consider the following code:
index.php

<?php

include("even.php");

echo "<br>Above File is Included"

?>

Output: Now, if we don’t have a file named even.php, then in the case of the include(), the
following output will be shown with warnings about a missing file, but at least the output will
be shown from the index.php file:

Warning message in include() function

In the case of the require(), if the file PHP file is missing, a fatal error will rise and no output is
shown and the execution halts.

Warning message in require() function


This is the only difference. This also shows that require() function is better than the include()
function since the script should not continue executing if files are missing or such an error is
generated.

PHP File Handling


File handling in PHP is used to you to create, open, read, write, delete, and manipulate files on
a server. It is used when you need to store data persistently or handle files uploaded by
users. PHP provides several built-in functions to make file handling easy and secure.

Common File Handling Functions in PHP


fopen() – Opens a file
fclose() – Closes a file
fread() – Reads data from a file
fwrite() – Writes data to a file
file_exists() – Checks if a file exists
unlink() – Deletes a file

What is File Handling in PHP?


File handling is the process of interacting with files on the server, such as reading file, writing to
a file, creating new files, or deleting existing ones. File handling is essential for applications that
require the storage and retrieval of data, such as logging systems, user-generated content, or
file uploads.

Opening and Closing Files


Before you can read or write to a file, you need to open it using the fopen() function, which
returns a file pointer resource. Once you’re done working with the file, you should close it
using fclose() to free up resources.
PHP
<?php

// Open the file in read mode

$file = fopen("gfg.txt", "r");

if ($file) {

echo "File opened successfully!";

fclose($file); // Close the file

} else {
echo "Failed to open the file.";

?>

File Modes in PHP


Files can be opened in any of the following modes:
“w” – Opens a file for writing only. If file does not exist then new file is created and if file
already exists then file will be truncated (contents of file is erased).
“r” – File is open for reading only.
“a” – File is open for writing only. File pointer points to end of file. Existing data in file is
preserved.
“w+” – Opens file for reading and writing both. If file not exist then new file is created and if file
already exists then contents of file is erased.
“r+” – File is open for reading and writing both.
“a+” – File is open for write/read. File pointer points to end of file. Existing data in file is
preserved. If file is not there then new file is created.
“x” – New file is created for write only.

Reading from Files


There are two ways to read the contents of a file in PHP. These are –
1. Reading the Entire File
You can read the entire content of a file using the fread() function or the file_get_contents()
function.
PHP
<?php

$file = fopen("gfg.txt", "r");

$content = fread($file, filesize("gfg.txt"));

echo $content;

fclose($file);

?>
2. Reading a File Line by Line
You can use the fgets() function to read a file line by line.
PHP
<?php

$file = fopen("gfg.txt", "r");

if ($file) {

while (($line = fgets($file)) !== false) {

echo $line . "<br>";

fclose($file);

?>

Writing to Files
You can write to files using the fwrite() function. It writes data to an open file in the specified
mode.
PHP
<?php

// Open the file in write mode

$file = fopen("gfg.txt", 'w');

if ($file) {

$text = "Hello world\n";

fwrite($file, $text);

fclose($file);

?>

Deleting Files
Use the unlink() function to delete the file in PHP.
PHP
<?php

if (file_exists("gfg.txt")) {

unlink("gfg.txt");

echo "File deleted successfully!";

} else {

echo "File does not exist.";

?>

PHP | Uploading File


Have you ever wondered how websites build their system of file uploading in PHP? Here we
will come to know about the file uploading process. A question which you can come up with –
‘Are we able to upload any kind of file with this system?’. The answer is yes, we can upload files
with different types of extensions.
Approach: To run the PHP script we need a server. So make sure you have the XAMPP
server or WAMP server installed on your windows machine.
HTML code snippet: Below is the HTML source code for the HTML form for uploading the file to
the server. In the HTML <form> tag, we are using “enctype=’multipart/form-data” which is an
encoding type that allows files to be sent through a POST method. Without this encoding, the
files cannot be sent through the POST method. We must use this enctype if you want to allow
users to upload a file through a form.
index.html:
HTML
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>File Upload Form</title>

</head>

<body>

<form action="file-upload-manager.php" method="post" enctype="multipart/form-data">


<!--multipart/form-data ensures that form data is going to be encoded as MIME data-->

<h2>Upload File</h2>

<label for="fileSelect">Filename:</label>

<input type="file" name="photo" id="fileSelect">

<input type="submit" name="submit" value="Upload">

<!-- name of the input fields are going to be used in our php script-->

<p><strong>Note:</strong>Only .jpg, .jpeg, .png formats allowed to a max size of 2MB.</p>

</form>

</body>

</html>

Now, time to write a PHP script which is able to handle the file uploading system. file-upload-
manager.php
PHP
<?php

// Check if the form was submitted

if($_SERVER["REQUEST_METHOD"] == "POST")

// Check if file was uploaded without errors

if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)

$allowed_ext = array("jpg" => "image/jpg",

"jpeg" => "image/jpeg",

"gif" => "image/gif",

"png" => "image/png");

$file_name = $_FILES["photo"]["name"];

$file_type = $_FILES["photo"]["type"];

$file_size = $_FILES["photo"]["size"];

// Verify file extension

$ext = pathinfo($filename, PATHINFO_EXTENSION);


if (!array_key_exists($ext, $allowed_ext))

die("Error: Please select a valid file format.");

// Verify file size - 2MB max

$maxsize = 2 * 1024 * 1024;

if ($file_size > $maxsize)

die("Error: File size is larger than the allowed limit of 2MB");

// Verify MYME type of the file

if (in_array($file_type, $allowed_ext))

// Check whether file exists before uploading it

if (file_exists("upload/".$_FILES["photo"]["name"]))

echo $_FILES["photo"]["name"]." already exists!";

else

move_uploaded_file($_FILES["photo"]["tmp_name"],

"uploads/".$_FILES["photo"]["name"]);

echo "Your file uploaded successfully.";

else

echo "Error: Please try again!";

else

echo "Error: ". $_FILES["photo"]["error"];

?>
In the above script, once we submit the form, later we can access the information via a PHP
superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built
functions are playing a major role. After we are done with uploading a file, in the script we will
check the request method of the server, if it is the POST method then it will proceed otherwise
the system will throw an error. Later on, we accessed the $_FILES array to get the file name,
file size, and type of the file. Once we got those pieces of information, then we validate the size
and type of the file. In the end, we search in the folder, where the file is to be uploaded, for
checking if the file already exists or not. If not, we have used move_uploaded_file() to move
the file from the temporary location to the desired directory on the server and we are done.

PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that
the site can retrieve to personalize the page when the user visits the website next time. A
cookie can only be read from the domain that it has been issued from. Cookies are usually set
in an HTTP header but JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie
will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);

Parameters: The setcookie() function requires six arguments in general which are:
Name: It is used to set the name of the cookie.
Value: It is used to set the value of the cookie.
Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be
accessed.
Path: It is used to specify the path on the server for which the cookie will be available.
Domain: It is used to specify the domain for which the cookie is available.
Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection
exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury Car to
it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
PHP

<!DOCTYPE html>
<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

echo "cookie is created."

?>

<p>

<strong>Note:</strong>

You might have to reload the

page to see the value of the cookie.

</p>

</body>

</html>

Note: Only the name argument in the setcookie() function is mandatory. To skip an argument,
the argument can be replaced by an empty string(“”).
Output:

Cookie creation in PHP

Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a cookie is set
or not before accessing its value. Therefore to check whether a cookie is set or not, the PHP
isset() function is used. To check whether a cookie “Auction_Item” is set or not, the isset()
function is executed as follows:
Example: This example describes checking whether the cookie is set or not.
PHP

<!DOCTYPE html>
<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

if (isset($_COOKIE["Auction_Item"]))

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

else

echo "No items for auction.";

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:

Checking for the cookie to be set

Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal variable
is used. It is an associative array that contains a record of all the cookies values sent by the
browser in the current request. The records are stored as a list where the cookie name is used
as the key. To access a cookie named “Auction_Item”, the following code can be executed.
Example: This example describes accessing & modifying the cookie value.
PHP

<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:

Accessing the Cookie value

Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a
cookie, the setcookie() function is called by passing the cookie name and other arguments or
empty strings but however this time, the expiration date is required to be set in the past. To
delete a cookie named “Auction_Item”, the following code can be executed.
Example: This example describes the deletion of the cookie value.
PHP
<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

setcookie("Auction_Item", "", time() - 60);

?>

<?php

echo "cookie is deleted"

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:

Deleting the Cookie

Important Points:
If the expiration time of the cookie is set to 0 or omitted, the cookie will expire at the end of
the session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used to create the
cookie in order to ensure that the correct cookie is deleted.
PHP | Sessions

What is a session?
In general, session refers to a frame of communication between two medium. A PHP session
is used to store data on a server rather than the computer of the user. Session identifiers or
SID is a unique number which is used to identify every user in a session based environment.
The SID is used to link the user with his information on the server like posts, emails etc.
How are sessions better than cookies?
Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to
easily modify the content of the cookie. Addition of harmful data by the attackers in the
cookie may result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data
each time the user views a page. Every time the browser requests a URL to the server, all the
cookie data for that website is automatically sent to the server within the request.
Below are different steps involved in PHP sessions:
Starting a PHP Session: The first step is to start up a session. After a session is started, session
variables can be created to store information. The PHP session_start() function is used to
begin a new session.It also creates a new session ID for the user.
Below is the PHP code to start a new session:

<?php

session_start();

?>

Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
array.The stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber and Name:

<?php

session_start();

$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";

?>

Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name is
shown below:

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';

echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Output:
The Name of the student is :Ajay

The Roll number of the student is :11

Destroying Certain Session Data: To delete only a certain session data,the unset feature can
be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:

<?php

session_start();

if(isset($_SESSION["Name"])){

unset($_SESSION["Rollnumber"]);

}
?>

Destroying Complete Session: The session_destroy() function is used to completely destroy a


session. The session_destroy() function does not require any argument.

<?php

session_start();

session_destroy();

?>

Important Points
The session IDs are randomly generated by the PHP engine .
The session data is stored on the server therefore it doesn’t have to be sent with every
browser request.
The session_start() function needs to be called at the beginning of the page, before any
output is generated by the script in the browser.

Implementing callback in PHP

Last Updated : 21 Dec, 2018

In PHP, callback is a function object/reference with type callable. A callback/callable variable


can act as a function, object method and a static class method. There are various ways to
implement a callback. Some of them are discussed below:
Standard callback: In PHP, functions can be called using call_user_func() function where
arguments is the string name of the function to be called.
Example:

<?php
// PHP program to illustrate working

// of a standard callback

// Function to print a string

function someFunction() {

echo "Geeksforgeeks \n";

// Standard callback

call_user_func('someFunction');

?>

Output:
Geeksforgeeks

Static class method callback: Static class methods can be called by using call_user_func() where
argument is an array containing the string name of class and the method inside it to be called.
Example:

<?php

// PHP program to illustrate working

// of a Static class method callback

// Sample class

class GFG {

// Function used to print a string

static function someFunction() {

echo "Parent Geeksforgeeks \n";

class Article extends GFG {


// Function to print a string

static function someFunction() {

echo "Geeksforgeeks Article \n";

// Static class method callback

call_user_func(array('Article', 'someFunction'));

call_user_func('Article::someFunction');

// Relative Static class method callback

call_user_func(array('Article', 'parent::someFunction'));

?>

Output:
Geeksforgeeks Article

Geeksforgeeks Article

Parent Geeksforgeeks

Object method callback: Object methods can be called by using call_user_func() where
argument is an array containing the object variable and the string name of method to be
called. Object method can also be called if they are made invokable using __invoke() function
definition. In this case, argument to the call_user_func() function is the object variable itself.
Example:

<?php

// PHP program to illustrate working

// of a object method callback

// Sample class

class GFG {

// Function to print a string


static function someFunction() {

echo "Geeksforgeeks \n";

// Function used to print a string

public function __invoke() {

echo "invoke Geeksforgeeks \n";

// Class object

$obj = new GFG();

// Object method call

call_user_func(array($obj, 'someFunction'));

// Callable __invoke method object

call_user_func($obj);

?>

Output:
Geeksforgeeks

invoke Geeksforgeeks

Closure callback: Closure functions can be made callable by making standard calls or mapping
closure function to array of valid arguments given to the closure function
using array_map() function where arguments are the closure function and an array of its valid
arguments.
Example:

<?php

// PHP program to illustrate working

// of a closure callback
// Closure to print a string

$print_function = function($string) {

echo $string."\n";

};

// Array of strings

$string_array = array("Geeksforgeeks", "GFG", "Article");

// Callable closure

array_map($print_function, $string_array);

?>

Output:
Geeksforgeeks

GFG

Article

You might also like