php2
php2
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.
<?php
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";
?>
Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
RAM
ZACK
RAGHAV
<?php
$round = count($name_one);
?>
Output:
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav
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
"Ram"=>"Rani", "Salim"=>"Sara",
"Raghav"=>"Ravina");
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
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
$name_one = [
];
echo "Husband is " . $val . " and Wife is " . $val_value . "\n";
$keys = array_keys($name_one);
$round = count($name_one);
?>
Output:
Looping using foreach:
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
$favorites = array(
array(
),
array(
),
array(
);
// Accessing elements
?>
Output:
Dave Punk email-id is: [email protected]
<?php
$favorites = array(
),
),
);
$keys = array_keys($favorites);
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.
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
// multidimensional array
// Creating multidimensional
// array
$myarray = array(
// start from 0
);
print_r($myarray);
?>
Output
Array
)
[1] => Array
$marks = array(
),
),
),
);
print_r($marks);
?>
Output
Display Marks:
Array
[C] => 95
[DCO] => 85
[FOL] => 74
)
[C] => 78
[DCO] => 98
[FOL] => 46
[C] => 88
[DCO] => 46
[FOL] => 99
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
// dimensional 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] => 1
[1] => 2
[0] => 3
[1] => 4
[0] => 5
[1] => 6
)
[1] => Array
[0] => 7
[1] => 8
// multidimensional array
// Creating multidimensional
// associative array
$marks = array(
),
),
),
);
// using dimensions
// Ankit in C subject
foreach($marks as $mark) {
?>
Output
95
95 85 74
78 98 46
88 46 99
Example: Sort the array elements in ascending order using PHP sort() function.
PHP
<?php
sort($arr);
print_r($arr);
?>
Output
Array
[0] => 2
[1] => 13
[2] => 22
[3] => 40
[4] => 61
Example: Sort the array elements in descending order using PHP rsort() function.
PHP
<?php
rsort($arr);
print_r($arr);
?>
Output
Array
[0] => 61
[1] => 40
[2] => 22
[3] => 13
[4] => 2
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
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
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
Example: Sort an array using comparison function (user defined) in uasort() function.
PHP
<?php
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_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(){
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>
<button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if(empty($name)){
} 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>
<button type="submit">SUBMIT</button>
</form>
<?php
$nm=$_POST['name'];
$age=$_POST['age'];
?>
</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'];
?>
</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.
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);
{
echo "Welcome ". $_GET['name']. "<br />";
exit();
?>
<html>
<body>
</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 (preg_match("/[^A-Za-z'-]/",$_POST['name'] ))
exit();
?>
<html>
<body>
</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.
Regular
Expression Matches
[abc] a, b, or c
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 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.
{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.
Special Character Classes in Regular Expressions: Let us look into some of the special characters
used in regular expressions.
Shorthand Character Sets: Let us look into some shorthand character sets available.
Shorthand Meaning
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.
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 string
if(preg_match($regex, $nameString)) {
else {
?>
Output:
Name string matching with regular expression
Example 2:
<?php
$regex = "/<b>(.*)<\/b>/U";
// Declare a string
?>
Output:
John
Developer
Example 3:
<?php
$regex = "([0-9]+)";
// Declare a string
$replaceWith = "2002";
// Display result
echo $original;
?>
Output:
Completed graduation in 2002
Example 4:
<?php
<?php
// Declare a string
$ip = "134.645.478.670";
$regex = "/\./";
// Use preg_split() function to
// an array
?>
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.
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.
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'])))
else
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
?>
<html>
<head>
</head>
<body>
<fieldset>
<?php
if (isset($_POST['submit']))
if (isset($error))
. $error . "</p>";
}
?>
FirstName:
<span style="color:red;">*</span>
<br>
<br>
Last Name:
<span style="color:red;">*</span>
<br>
<br>
Address:
<span style="color:red;">*</span>
<br>
<br>
Email:
<span style="color:red;">*</span>
<br>
<br>
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>
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
if(!isset($error))
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<thead>";
echo "<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
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.
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
$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 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
?>
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";
?>
Output:
1512486297
Example: The below example explains the usage of the mktime() function in PHP.
PHP
<?php
?>
Output:
1511652110
The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.
// File to be included
?>
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");
?>
Output:
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
?>
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:
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");
?>
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:
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.
if ($file) {
} else {
echo "Failed to open the file.";
?>
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
if ($file) {
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
if ($file) {
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");
} else {
?>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<!-- name of the input fields are going to be used in our php script-->
</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
if($_SERVER["REQUEST_METHOD"] == "POST")
$file_name = $_FILES["photo"]["name"];
$file_type = $_FILES["photo"]["type"];
$file_size = $_FILES["photo"]["size"];
if (in_array($file_type, $allowed_ext))
if (file_exists("upload/".$_FILES["photo"]["name"]))
else
move_uploaded_file($_FILES["photo"]["tmp_name"],
"uploads/".$_FILES["photo"]["name"]);
else
else
?>
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
?>
<html>
<body>
<?php
?>
<p>
<strong>Note:</strong>
</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:
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
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
else
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Output:
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
?>
<html>
<body>
<?php
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Output:
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
?>
<html>
<body>
<?php
?>
<?php
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Output:
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();
?>
Output:
The Name of the student is :Ajay
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"]);
}
?>
<?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.
<?php
// PHP program to illustrate working
// of a standard callback
function someFunction() {
// 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
// Sample class
class GFG {
call_user_func(array('Article', 'someFunction'));
call_user_func('Article::someFunction');
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
// Sample class
class GFG {
// Class object
call_user_func(array($obj, 'someFunction'));
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
// of a closure callback
// Closure to print a string
$print_function = function($string) {
echo $string."\n";
};
// Array of strings
// Callable closure
array_map($print_function, $string_array);
?>
Output:
Geeksforgeeks
GFG
Article