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

Module 4 PHP

Php programming

Uploaded by

jumanabeevi.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Module 4 PHP

Php programming

Uploaded by

jumanabeevi.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

PHP MODULE 4 S.

MODULE 4

WORKING WITH PHP

INTRODUCTION

Arrays in PHP are a type of data structure that allows storing multiple elements
under a single variable. An array in PHP is actually an ordered. A map is a type
that associates values to keys. The array elements can be accessed using their
index or key (array index).

CREATING AN ARRAY

There are three main ways to create array in PHP script.

1. Creating array by direct assignment.

This is the simple way to declare an array.

<?php

$color[0] = "Red";

$color[1] = "Green";

$color[2] = "Blue";

?>

2. Creating array by using array() construct

Here array is created through array construct. The array() takes a comma
separated list of elements to be stored

<?php

$colour = array(“Red”, “Green”, “Blue”);

?>
PHP MODULE 4 S.A

In this array named colour is assigned three elements with indices 0, 1, 2


respectively.

An array with no elements can be created as follows:

$arr = array();

Or arrays can be created using the special syntax mentioning the key
value pair.

$fruits = array(‘red’ => ‘apple’, ‘yellow’ => ‘banana’ , ‘green’ =>


‘pear’);

Here keys and values are separated using special symbol =>.

3. By calling a function that happens to return an array as its value.

The final way to create an array in a script is to call a function that returns
an array.

TYPES OF ARRAYS

There are three different kinds of arrays and each array value is accessed using
an ID which is called array index.

 Numeric array − An array with a numeric index. Values are stored


and accessed in linear fashion.

 Associative array − An array with strings as index. This stores


element values in association with key values .Specific key is assigned
for each value. [key value pairs]

 Multidimensional array − An array containing one or more arrays and


values are accessed using multiple indices.
PHP MODULE 4 S.A

Indexed Arrays/Numeric arrays

An indexed or numeric array stores each array element with a numeric index.

Syntax:

$arr = array( val1, val2, val3, ... );

Example

<?php

$colors = array("Red", "Green", "Blue");

?>
or
<?php

$colors[0] = "Red";

$colors[1] = "Green";

$colors[2] = "Blue";

?>
Associative Arrays

In associative array, elements are stored as key-value pairs. I n These types


of arrays every value can be assigned with a user-defined key. The key
can be a string. The value can be of any type.

Syntax: $arr = array( key=>val, key=>val, key=>value, ... );

Example

<?php

// Define an associative array

$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);

?>
PHP MODULE 4 S.A

Or it can be written as

<?php

$ages["Peter"] = "22";

$ages["Clark"] = "32";

$ages["John"] = "28";

?>

Multidimensional Arrays

The multidimensional array is an array in which each element can also be an


array and each element in the sub-array can be an array. In other words, a multi-
dimensional array is an array of arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep.

Multidimensional array can be accessed using a set of square brackets such as

print $arr[0][1];

Syntax:

array( array( val11, val12, ...)

array( val21, val22, ...)

... );

Example:
<?php
$myarray = array(
array("Ankit", "Ram", "Shyam"),
array(“Tcr", "Trichy", "Kanpur")
);
PHP MODULE 4 S.A

// Display the array information


var_dump($myarray);
?>

Viewing Array Structure and Values

The structure and values of any array can be viewed by using one of two
statements — var_dump() or print_r(). The print_r() statement, however,
gives somewhat less information. The var_dump() function is used to dump
information about a variable. This function displays structured information such
as type and value of the given variable.

PHP ARRAY OPERATORS

The PHP array operators are used to compare arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have


the same key/value pairs.

=== Identity $x === $y Returns true if $x and $y have


the same key/value pairs in the
same order and of the same
types

!= Inequality $x != $y Returns true if $x is not


equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to


$y

!== Non-identity $x !== $y Returns true if $x is not identical


to $y
PHP MODULE 4 S.A

Deleting from Array

unset() Function: The unset() function is used to remove element from the
array. The unset function is used to destroy any other variable and to delete any
element of an array

<?php
$arr = array('G', 'E', 'E', 'K', 'S');
// Display the array element
print_r($arr);
unset($arr[2]);
print_r($arr);
?>
Output

Array ( [0] => G [1] => E [3] => K [4] => S )

In the example the second element is deleted

PHP ARRAY FUNCTIONS


PHP supports a large number of built in functions. The array functions are part
of PHP core. The commonly used array functions are:

array() – It creates an array.

<?php
$cars=array("Volvo","BMW","Toyota");

var_dump($cars);

?>
array_change_key_case() - The function changes all keys in an array to
lowercase or uppercase.

 CASE_LOWER - Default value. Changes the keys to lowercase


 CASE_UPPER - Changes the keys to uppercase

Syntax - array_change_key_case(array, case);


PHP MODULE 4 S.A

Example:

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

print_r(array_change_key_case($age,CASE_UPPER));

?>

Output

array ( [PETER] => 35 [BEN] => 37 [JOE] => 43 )

array_chunk - The function splits an array into chunks of new arrays.

Syntax - array_chunk(array, size);

Example

<?php

$input = array('abc', 'bcd', 'cde', 'def');

print_r(array_chunk($input, 2));

?>
In this example the given array is divided into chunks of 2.
Output

Array
(
[0] => Array
(
[0] => abc
[1] => bcd
) [1] =>
Array(
[0] => cde
[1] => def ))
PHP MODULE 4 S.A

array_combine() – The function creates an array, by using the elements


from one "keys" array and one "values" array. Both arrays must have equal
number of elements.

Syntax

array_combine(keys, values);

Example

<?php

$fname=array("Peter","Ben","Joe");

$age=array("35","37","43");

$c=array_combine($fname,$age);

print_r($c);

?>

Output

Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

array_count_values() – The function counts the occurrence of all the values


of an array.

Syntax

array_count_values(array);

Example

<?php

$a=array("A","Cat","Dog","A","Dog");

print_r(array_count_values($a));

?>
PHP MODULE 4 S.A

Output

Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )

array_diff() – The function compares the values of two (or more) arrays, and
returns the differences. This function compares the values of two (or more)
arrays, and returns an array that contains the entries from array1 that are not
present in array2 or array3, etc.

Syntax - array_diff(array1, array2, array3, ...);

Example

<?php

$a1=array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");

$a2=array("e"=>"red", "f"=>"green", "g"=>"blue");

$result=array_diff($a1,$a2);

print_r($result);

?>
Output

Array ( [d] => yellow )

array_fill() – The function fills an array with values.

array_fill(index, number, value);

Parameter Description

index Required. The first index of the returned array

number Required. Specifies the number of elements to insert

value Required. Specifies the value to use for filling the array
PHP MODULE 4 S.A

<?php

$a1=array_fill(3,4,"blue");

$b1=array_fill(0,1,"red");

print_r($a1);

echo "<br>";

print_r($b1);

?>

Output

Array ( [3] => blue [4] => blue [5] => blue [6] => blue )

Array ( [0] => red )

array_flip() - The array_flip() function flips/exchanges all keys with their


associated values in an array.(keys and values are exchanged).

Syntax

array_flip(array);

Example

<?php
$a1=array("a"=>"red","b"=>"green");
$result=array_flip($a1);
print_r($result);
?>
Output
Array ( [red] => a [green] => b
PHP MODULE 4 S.A

array_intersect() – The function compares the values of two (or more)arrays,


and returns the matches.

Syntax - array_intersect(array1, array2, array3, ...);

Example

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_intersect($a1,$a2);

print_r($result);

?>

Output

Array ( [a] => red [b] => green [c] => blue )

array_key_exists() – The function checks whether the key exists in an array.

Syntax

array_key_exists(key, array);

array_keys() - The function returns an array containing the keys.

<?php

$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");

print_r(array_keys($a));

?>

Output

Array ( [0] => Volvo [1] => BMW [2] => Toyota )
PHP MODULE 4 S.A

array_merge() - The function merges one or more arrays into one array.

Syntax

array_merge(array1, array2, array3, ...);

Example

<?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_merge($a1,$a2));

?>

Output

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

array_pop() -The function deletes the last element of an array.

Syntax

array_pop(array);

Example

<?php

$a=array("red","green","blue");

array_pop($a);

print_r($a);

?>
Output

Array ( [0] => red [1] => green )


PHP MODULE 4 S.A

array_product() – The function calculates and returns the product of an


array.

Syntax

array_product(array);

Example

<?php

$a=array(5,5);

echo(array_product($a));

?>

Output

25

array_push() - The function inserts one or more elements to the end of an


array.

Syntax

array_push(array, value1, value2, ...);

Example

<?php

$a=array("red","green");

array_push($a,"blue","yellow");

print_r($a);

?>
Output

Array ( [0] => red [1] => green [2] => blue [3] => yellow )
PHP MODULE 4 S.A

array_reverse() - The function returns an array in the reverse order.

Syntax

array_reverse(array);

Example

<?php

$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");

print_r(array_reverse($a));

?>

Output

Array ( [c] => Toyota [b] => BMW [a] => Volvo )

array_replace() - The function replaces the values of the first array with the
values from following arrays.

Syntax

array_replace(array1, array2, array3, ...);

Example

<?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_replace($a1,$a2));

?>

Output
Array ( [0] => blue [1] => yellow )
PHP MODULE 4 S.A

array_search() -The function search an array for a value and returns the key
of the found value.

Syntax - array_search(value, array);

Here value refers to the item to be searched in the array.

Example

<?php

$a=array("a"=>"red","b"=>"green","c"=>"blue");

echo array_search("red",$a);

?>

Output

array_slice() - The function returns selected parts of an array.

Syntax - array_slice(array, start, length);

The length parameter is optional and it specifies the length of the returned array.

Here in the example it starts the slice from the third array element(index 2), and
return the rest of the elements in the array:

Example

<?php

$a=array("red","green","blue","yellow","brown");

print_r(array_slice($a,2));

?>
Output

Array ( [0] => blue [1] => yellow [2] => brown )
PHP MODULE 4 S.A

array_splice() - The function removes selected elements from an array and


replaces it with new elements. The function also returns an array with the
removed elements. Here in the example

Syntax

array_splice(array, start, length, array);

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>

Output

Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )

array_sum() - The function returns the sum of all the values in the array.

Syntax

array_sum(array);

Example

<?php
$a=array(5,15,25);
echo array_sum($a);
?>
Output
45
array_unique() – The function removes duplicate values from an array. If
two or more array values are the same, the first appearance will be kept and the
other will be removed.
PHP MODULE 4 S.A

<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>

Output

Array ( [a] => red [b] => green )

array_values()- The function returns an array containing all the values of an


array.

Syntax

array_values(array);

Example

<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>

Output

Array ( [0] => Peter [1] => 41 [2] => USA )

count() – The function returns the number of elements in an array.


Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output

3
PHP MODULE 4 S.A

shuffle() – The function randomizes the order of the elements in the array.

Example

<?php
$my_array=array("red","green","blue","yellow","purple");

shuffle($my_array);
print_r($my_array);
?>

Output

Array ( [0] => yellow [1] => purple [2] => red [3] => blue [4] => green )

sort() – The function sorts an indexed array in ascending order.

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>

Output

BMW
Toyota
Volvo
PHP MODULE 4 S.A

rsort() - The function sorts an indexed array in descending order.

Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
Output

Volvo
Toyota
BMW

ksort() – The function sorts an associative array in ascending order, according


to the key.

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);

print_r($age);

Output

Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )

krsort() - The function sorts an associative array in descending order,


according to the key.
PHP MODULE 4 S.A

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);

print_r($age)
?>

Output

Array ( [Peter] => 35 [Joe] => 43 [Ben] => 37 )

asort() - The function sorts an associative array in ascending order, according


to the value.

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);

print_r($age)
?>

Output

Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )


PHP MODULE 4 S.A

arsort() - The function sorts an associative array in descending order,


according to the value.

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);

print_r($age)
?>

Output

Array ( [Joe] => 43 [Ben] => 37 [Peter] => 35 )

range() – The function creates an array containing a range of elements.

<?php
$number=range(0,5);
print_r($number);
?>

Output

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 )

ITERATION THROUGH AN ARRAY

PHP provides several ways to traverse arrays using both array iteration
functions and language constructs: foreach, list/each, for loops etc.
PHP MODULE 4 S.A

foreach Loop:

The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array. It loops through a block of code for each element in
an array.

Syntax

foreach ($array as $value)

{
code to be executed;
}

or

foreach( $array as $key => $element)

// PHP Code to be executed

In the first example, for every loop iteration, the value of the current array
element is assigned to $value and the array pointer is moved by one, until it
reaches the last array element.

<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
PHP MODULE 4 S.A

The following example will output both the keys and the values of the given
array ($age):

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val)

{
echo "$x = $val<br>";
}
?>

Output

Peter = 35
Ben = 37
Joe = 43

list() function

The list() function is used to assign values to a list of variables in one operation.
This is a language construct. The first element in the given array is assigned to
the first variable passed and the second element to the second variable and so
on,

Syntax:

list($variable1, $variable2 ... );

Example

<?php
$my_array = array("php","java","python");
list($a, $b, $c) = $my_array;
PHP MODULE 4 S.A

echo "I like, $a, $b and $c.";


?>

Output:

I like php, java, python

STRING IN PHP

Strings are sequences of characters that can be treated as a unit. It can be


enclosed in either single or double quotes. Strings can be represented using
single quotes, double quotes and in heredoc syntax.

<?php

$srt1 = "This is a String";

$str2 = 'This is also a String';

?>

If strings are enclosed in single quotation almost no processing is done. All the
escape sequences like \t or \n, will be printed as specified instead of having
any special meaning. If it is enclosed in double quotes PHP will merge the
values of any variable we include. It interprets the Escape sequences. Each
variable will be replaced by its value.

$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.

A string can also be specified using heredoc statement. It is used for specifying
large chunk of statements. The operator in heredoc statement is <<< operator.
<?php
$str = <<<demo
PHP MODULE 4 S.A

welcome to the best tutorial site .


This is an example for heredoc statement
demo;
echo $str;
?>
PHP STRING FUNCTIONS

PHP provides various string functions to access and manipulate strings. The
PHP string functions are part of the PHP. No external installation is required to
use these functions.

strlen() – The function return the length of a String.

The PHP strlen() function returns the length of a string including white spaces.
If the string is empty the function will return 0.

syntax

strlen(string);

Example

<?php
echo strlen("Hello world!"); // outputs 12
?>

strpos() – The function finds the position of the first occurrence of a string
inside another string.

Note: The strpos() function is case-sensitive.


PHP MODULE 4 S.A

Syntax

strpos(string, find, start);

Parameter Values

Parameter Description

string Required. Specifies the string to search

find Required. Specifies the string to find

start Optional. Specifies where to begin the search

Example

<?php
echo strpos("I like php I like php too!","php");
?>

Output

strrpos() – The function finds the position of the last occurrence of a string
inside another string.
PHP MODULE 4 S.A

Note: The strrpos() function is case-sensitive.

Syntax

strrpos(string,find,start);

Example

<?php

echo strrpos("I like php I like php too!","php");

?>

Output

19

stripos() – The function finds the position of the first occurrence of a string
inside another string.

Note: The stripos() function is case-insensitive.

<?php
echo stripos("I love php, I love php too!","PHP");
?>
Output
7

strripos() –The function finds the position of the last occurrence of a string
inside another string.
PHP MODULE 4 S.A

Note: The strripos() function is case-insensitive.

<?php

echo strripos("I love php, I love php too!","PHP");

?>

Output

19

strstr() – The function searches for the first occurrence of a string inside
another string. Returns the rest of the string (from the matching point) to the end
of the string.

strstr(string,search);

Note: This function is case-sensitive.

<?php

echo strstr("Hello world!","world");

?>

Output

world!

stristr() –The function searches for the first occurrence of a string inside
another string.

Note: This function is case-insensitive.


PHP MODULE 4 S.A

<?php

echo stristr("Hello world!","WORLD");

?>

Output

world!

substr() –The function returns a part of a string.

Returns the extracted part of a string, or FALSE on failure, or an empty string

Syntax

substr(string,start,length);

Parameter Values

Parameter Description

string Required. Specifies the string to return a part of

start Required. Specifies where to start in the string

 A positive number - Start at a specified position


in thestring
 A negative number - Start at a specified position
from theend of the string

 0 - Start at the first character in string

length Optional. Specifies the length of the returned string.


Default isto the end of the string.
PHP MODULE 4 S.A

<?php

echo substr("Hello world",6);

?>

Output

world

strcmp() –The function compares two strings. It is a binary safe string


comparison.

Note: The strcmp() function case-sensitive.

Parameter Description

string1 Required. Specifies the first string to compare

string2 Required. Specifies the second string to compare

Return This function returns:


Value:
 0 - if the two strings are equal
 <0 - if string1 is less than string2
 >0 - if string1 is greater than string2
Syntax -

strcmp(string1,string2);

Example

<?php

echo strcmp("Hello world!","Hello world!");

?>
PHP MODULE 4 S.A

Output

Example 2

<?php

$str1 = "PHP";

$str2 = "PYTHON";

echo strcmp($str1, $str2);

echo strcmp($str2, $str1);

echo strcmp($str1, $str1);

?>

Output

-3
3
0

strncmp() - This is an inbuilt function in PHP which is used to compare first n


character of two strings. This function is case-sensitive which points that capitaland
small cases will be treated differently, during comparison.

<?php

echo strncmp("Hello world!","Hello earth!",6);

?>

Output
0
PHP MODULE 4 S.A

str_replace() - The function replaces some characters with some other


characters in a string. The first argument is the part of string that you want to
replace, second argument is the new text you want to include, and the last
argument is the string variable itself. This function is case-sensitive.

str_replace(find, replace, string);

Example

<?php

echo str_replace("Hello","Hi","Hello world!");

?>
Output
Hi World!

strrev() – The function reverses a string.

Syntax -

strrev(string);

Example

<?php

echo strrev("Hello World!");


?>

Output

!dlroW olleH

strtolower() : This function is used to convert every letter/character of a


string to lowercase.
PHP MODULE 4 S.A

<?php

$str = "WELCOME TO PHP";

echo strtolower($str);

?>

Output

welcome to php

strtoupper() – The function converts every letter/character of every word of


the string to uppercase.

Example

<?php

$str = "welcome to php";

echo strtoupper($str);

?>
Output

WELCOME TO PHP

ucfirst() – The function converts the first character of a string to uppercase.


Example

<?php

echo ucfirst("hello world!");

?>
Output

Hello world!

lcfirst() – The function converts the first character of a string to lowercase.


lcfirst(string);
PHP MODULE 4 S.A

Example

<?php

echo lcfirst("Hello world!");

?>

Output - hello world!

ucwords() – The function converts the first character of each word in a string
to uppercase.

Example

<?php

echo ucwords("hello world");

?>
Output

Hello World

str_word_count() - This function returns the number of words in the string.


This function is used in form field validation for some simple validations.

str_word_count( str);

Example

<?php

$str = "Welcome to PHP";

echo "Number of words in the string are: ". str_word_count($str);

?>
Output

Number of words in the string are: 3


PHP MODULE 4 S.A

trim() - The function removes whitespace and other predefined characters


from both sides of a string.

Related functions:

 ltrim() - Removes whitespace or other predefined characters from the left


side of a string
 rtrim() - Removes whitespace or other predefined characters from the
right side of a string

The printf() function outputs a formatted string.

The echo() outputs one or more strings.

Note: The echo() is not actually a function, so you are not required to use
parentheses with it.

PASSING INFORMATION BETWEEN PAGES

It is often required to pass values of variables between pages in a website. It


can be passed within a site or even outside the site. There are different methods
for passing values of the variables between pages and they are:

Passing variables between pages using URL

Variable values can be passed between pages through the URL (in address bar
of the browser). Here values are visible to the user and others as they appear in
PHP MODULE 4 S.A

the address bar and also in the browser history. This is not a secure way to
transfer sensitive data like password, etc.

Passing variables between pages using cookies

HTTP is a stateless protocol and thus values between page requests cannot be
preserved. So cookies or sessions are used to store the variables while
passing values between pages.

Cookies are stored at the client end and values can be passed between pages
using PHP. But here the client browser can reject accepting cookies by
changing the security settings of the browser. So this system can fail to pass
values between pages if user or client end settings are changed. But cookies are
quite useful in handling user entered values and passing them between pages.

Passing variable values between pages using session

Sessions are stored at the server end. This is one of the secured ways in which
the variables are passed between pages. Session variables hold information
about one single user, and are available to all pages in one application. The best
example of such a system is when we see our user-id after we log in. In
a member login system the user details are verified and once found correct, a
new session is created and with user id of the member and this value is stored at
server end. Every time a new page is opened by the browser, the server checks
the associated session value and display the user id. This system is more secure
and the member doesn't get any chance to change the values.
PHP MODULE 4 S.A

Passing variables between pages using URL

There are different ways by which values of variables can be passed between
pages. One of the ways is to use the URL to pass the values or data. Here one
main concern is that the data gets exposed in address bar of the browser and can
be easily accessible by using browser history. So it is not a good idea to pass
sensitive data like password through the URL to different pages or different
sites.

There are two ways the browser client can send information to the web server.

 The HTTP GET Method


 The HTTP POST Method

HTTP GET METHOD

The GET method passes arguments from one page to the next as part of the
URL query string. When used for form handling, GET appends the indicated
variable name and value to the URL in the action attribute with a question
mark separator and submits the whole thing to the Web server.

In this scheme, name/value pairs are joined with equal signs and different pairs
are separated by the ampersand.

example_form.php?name1=value1&name2=value2

Spaces are removed and replaced with the + character and any other non-
alphanumeric characters are replaced with a hexadecimal values. Before the
browser sends the information, it encodes it using a scheme called URL
encoding. After the information is encoded it is sent to the server. The server
will decode the special characters automatically.
PHP MODULE 4 S.A

<html>
<body>
<form action="registration.php" method="GET">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>

</html>

registration.php looks like this:

<html>

<body>

Welcome <?php echo $_GET["name"]; ?>

Your email address is <?php echo $_GET["email"]; ?>

</body>

</html>

 GET requests can be cached.


 GET requests remain in the browser history.
 GET requests can be bookmarked.
 GET requests should never be used when dealing with sensitive data
 GET requests have length restrictions.
 GET requests are only used to request data (not modify).
PHP MODULE 4 S.A

HTTP GET method should not be used in the following scenarios:

 While updating database or spread sheet.


 While passing sensitive information
 When there is large amount of data to be passed.
 When there is a file upload control in the page.

HTTP POST METHOD

The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.

 The POST method does not have any restriction on data size to be sent.

 The POST method can be used to send ASCII as well as binary data.

 The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP you can make sure
that your information is secure.

 The PHP provides $_POST associative array to access all the sent
information using POST method. 

coder.php

<?php
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
}
?>
PHP MODULE 4 S.A

<html>
<body>

<form action = "coder.php" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>

COMPARE GET METHOD AND POST METHOD

The following table compares the two HTTP methods: GET and POST.

GET POST

BACK Harmless. No need to resubmit Data will be re-submitted


button/Reload data. (the browser should alert
the user that the data are
about to be re-submitted)

Bookmarked Can be bookmarked Cannot be bookmarked


PHP MODULE 4 S.A

Cached Data can be cached Data cannot be cached

Encoding application/x-www-form- application/x-www-form-


type urlencoded urlencoded or
multipart/form-data. Use
multipart encoding for
binary data

History Parameters remain in browser Parameters are not saved in


history browser history

Restrictions When sending data, the GET No data length restrictions


on data length method adds the data to the
URL; and the length of a URL
is limited (maximum URL
length is 2048 characters)

Restrictions Only ASCII characters allowed No restrictions. Binary data


on data type is also allowed

Security GET is less secure because data In POST method the


sent is part of the URL parameters are not stored in
browser history or in web
PHP MODULE 4 S.A

Never use GET method when server logs. Data doesn’t


sending passwords or other show up in the address bar.
sensitive information!

Visibility Data is visible to everyone in Data is not displayed in the


the URL URL

PASSING VARIABLES BETWEEN PAGES USING COOKIES

Cookies are text files stored on the client computer and they are kept for
tracking purpose. PHP transparently supports HTTP cookies. It is a piece of
data used to store variables name, value along with information on the site from
which it came from and an expiration time.

PHP cookie is a small piece of information which is stored at client browser. It


is used to recognize the user. Cookie is created at server side and saved to client
browser. Text cookies are not executable but they can be used as spywares to
track user information.

There are three steps involved in identifying returning users −

 Server script sends a set of cookies to the browser. For example name,
age, or identification number etc.

 Browser stores this information on local machine for future use.

 When next time browser sends any request to web server then it sends
those cookies information to the server and server uses that information
to identify the user. 
PHP MODULE 4 S.A

A cookie can be used for authentication, storing site preferences, shopping cart
contents etc. A cookie consists of one or more name value pairs. Websites can
modify their own cookies.

Cookies are sent as a field in header of HTTP response by web server to web
browser.

Create Cookies with PHP

A cookie is created with the setcookie() function.

setcookie(name, value, expire, path, domain, secure, httponly);

Example
$value = “anyvalue”;
setcookie("Test", $value, time()+3600, "/~rasmus/", "example.com", 1,1);

Note: Only the name parameter is required. All other parameters are optional.

 Name − This sets the name of the cookie 

 Value − This sets the value of the named variable and is the content that
you actually want to store.

 Expiry − This specify a future time in seconds since 00:00:00 GMT on


1st Jan 1970. After this time cookie will become inaccessible. If this
parameter is not set then cookie will automatically expire when the Web
Browser is closed.
PHP MODULE 4 S.A

 Path − This specifies the directories for which the cookie is valid 

 Domain − This can be used to specify the domain name. All cookies are
only valid for the host and domain which created them.

 Security − This can be set to 1 to specify that the cookie should only be
sent by secure transmission using HTTPS otherwise set to 0 which mean
cookie can be sent by regular HTTP.

 httponly – When true cookies will be accessible only through http


protocol.
PHP Create/Retrieve a Cookie

The value of the cookie can be retrieved using the global variable $_COOKIE.
The isset()function is used to find out if the cookie is set:.

<?php

$cookie_name = "user";

$cookie_value = "John Doe";

setcookie($cookie_name, $cookie_value, time() + 3600, "/");

?>

<html>

<body>

<?php

if(isset($_COOKIE[$cookie_name]))

echo "Cookie '" . $cookie_name . "' is set!<br>";

echo "Value is: " .$_COOKIE[$cookie_name];

}
else
PHP MODULE 4 S.A

echo "cookie is not set!";

?>

</body>

</html>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the
past:

Example

<?php

// set the expiration date to one hour ago

setcookie("user", "", time() - 3600);

?>

<html>

<body>

<?php

echo "Cookie 'user' is deleted.";

?>

</body>

</html>
PHP MODULE 4 S.A

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are
enabled. First create a test cookie with the setcookie() function, then count the
$_COOKIE array variable:

<?php

setcookie("test_cookie", "test", time() + 3600, '/');

?>

<html>

<body>

<?php

if(count($_COOKIE) > 0)

echo "Cookies are enabled.";

} else {

echo "Cookies are disabled.";

?>

</body>

</html>
PHP MODULE 4 S.A

PASSING VARIABLES BETWEEN PAGES USING SESSION

Since cookies are stored on user's computer it is possible for an attacker to


easily modify a cookie content to insert potentially harmful data in your
application that might break your application.

Also every time the browser requests a URL to the server, all the cookie data for
a website is automatically sent to the server within the request. It means if you
have stored 5 cookies on user's system, each having 4KB in size, the browser
needs to upload 20KB of data each time the user views a page, which can affect
your site's performance.

PHP session can be used to solve the above problem. A PHP session stores data
on the server computer. In a session based environment, every user is identified
through a unique number called session identifier or SID.

A session is a way to store information (in variables) to be used across multiple


pages.

By default, session variables last until the user closes the browser

Here data is kept in the server and a “key” (SID) is given to the client to
uniquely identify themselves.

The session IDs are randomly generated by the PHP.


PHP MODULE 4 S.A

Starting a PHP Session

Before storing information in session variables, a session should be started. To


begin a new session, simply call the PHP session_start() function. It will create
a new session and generate a unique session ID for the user.

The session_start() need to be executed before any other header calls.

The PHP code in the example below simply starts a new session.

<?php
// Starting session
session_start();

?>
PHP MODULE 4 S.A

Storing and Accessing Session Data

All session data are stored as key-value pairs in the $_SESSION[] super global
array. The stored data can be accessed during the lifetime of a session.

<?php
// Starting session
session_start();

// Storing session data


$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Hill";
?>
EXAMPLE
<?php
// Starting session
session_start();

// Accessing session data


echo $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>

Destroying a Session

If you want to remove certain session data, simply unset the corresponding key
of the $_SESSION associative array, as shown in the following example:

<?php
// Starting session
PHP MODULE 4 S.A

session_start();

// Removing session data


if(isset($_SESSION["lastname"]))
{
unset($_SESSION["lastname"]);
}
?>
To destroy a session completely, simply call the session_destroy() function.
This function does not need any argument and a single call destroys all the
session data.

<?php
// Starting session
session_start();

// Destroying session
session_destroy();
?>

Most sessions set a user-key on the user's computer that looks something like
this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
another page, it scans the computer for a user-key. If there is a match, it
accesses that session, if not, it starts a new session. The browser can send
session ID to server through cookie or as URL parameter. The length of the
session is determined by session timeout setting in php.ini file. The default is
24 minutes.
PHP MODULE 4 S.A

Difference Between Session and Cookies :

Cookie Session

Cookies are client-side files on a


local computer that hold user
information. Sessions are server-side files that contain user data.

Cookies end on the expiry time set by When the user quits the browser or logs out of the
the user. programmed, the session is over.

We can keep as much data as we like within a session,


The browser’s cookies have a however there is a maximum memory restriction of
maximum capacity of 4 KB. 128 MB that a script may consume at one time.

Because cookies are kept on the local


computer, we don’t need to run a To begin the session, we must use the session start()
function to start them. method.

Cookies are not secured. Session are more secured compare than cookies.

Cookies stored data in text file. Session save data in encrypted form.

Cookies stored on a limited data. Session stored unlimited data.

In PHP, to get the data from Cookies ,


$_COOKIES the global variable is In PHP , to set the data from Session, $_SESSION the
used global variable is used

In PHP, to destroy or remove the data stored within a


We can set an expiration date to delete session, we can use the session_destroy() function, and
the cookie’s data. It will automatically to unset a specific variable, we can use the unset()
delete the data at that specific time. function.
PHP MODULE 4 S.A

HTTP HEADERS

HTTP requests and reply messages are accompanied by a header consisting of


several header fields that define the parameters of an HTTP transaction. HTTP
headers let the client and the server pass additional information with an HTTP
request or response. An HTTP header consists of its case-insensitive name
followed by a colon (:), then by its value.

The four types of HTTP header fields are:

General: These headers are used by both client and servers. It contains general
information such as, Cache-control, Date, Connection etc.

Request: A request header is an HTTP header that can be used in an HTTP


request, and that doesn't relate to the content of the message. It contains client’s
configuration and supported formats. Request header includes- Accept, Accept-
Charset, Accept-Encoding, Cookie, Proxy-Authentication etc.

Response: The response header describes server configuration and information


about URL that was requested. It includes Location, Server, Set-Cookie, Last-
modified etc.

Entity: This header fields contains the format of the content being sent by
server and client. Headers like Content-Length, Content-Language, Content-
Encoding are entities headers.
PHP MODULE 4 S.A

The header() function

The header() function is used to send raw http headers. The header() are those
functions which manipulate information sent to the client or browser by the Web
server, before any other output has been sent.

header(header, replace, http_response_code);

the PHP header() function does not return any value.

<?php
header("HTTP/1.0 404 Not Found");
?>

The header() function can be used to set cookies.

Uses
o It changes the page location.
o It sets the time zone.
o This function sets the caching control.
o It initiates the force download.

header() for redirecting browser

The following code will redirect your user to some another page.

<?php
// This will redirect the user to the new location
header('Location: http://www.tester.com/');

//The below code will not execute after header


exit;
?>
PHP MODULE 4 S.A

<?php
header( "refresh:10;url=example.php");
echo 'You will be redirected in 10 seconds. If not please
click<ahref="example.php">here</a>.';
?>

header() to prevent browser to cache pages

By using the following code, you can prevent the browser to cache pages.

<?php
// PHP program to describes header function

// Set a past date


header("Cache-Control: no-cache");
?>

header() for downloading

<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');

Header() is used to prompt the user to save a generated PDF file (Content-
Disposition header is used to supply a recommended filename and force the
browser to display the save dialog box):

The header() can also be used for purposes like HTTP authentication, sending
specific errors to browse

You might also like