Sunteți pe pagina 1din 79

Graphic Era Hill University, Dehradun

PHP5

What is PHP?

 PHP stands for PHP: Hypertext Preprocessor


 PHP is a server-side scripting language, like ASP
 PHP scripts are executed on the server
 PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid, PostgreSQL, Generic ODBC, etc.)
 PHP is an open source software
 PHP is free to download and use

PHP is an HTML-embedded scripting language. Much of its syntax is


borrowed from C, Java and Perl with a couple of unique PHP-specific
features thrown in. The goal of the language is to allow web developers
to write dynamically generated pages quickly."

When someone visits your PHP webpage, your web server processes the
PHP code. It then sees which parts it needs to show to visitors(content
and pictures) and hides the other stuff(file operations, math calculations,
etc.) then translates your PHP into HTML. After the translation into
HTML, it sends the webpage to your visitor's web browser.

What is a PHP File?

 PHP files can contain text, HTML tags and scripts


 PHP files are returned to the browser as plain HTML
 PHP files have a file extension ".php"

What is MySQL?
 MySQL is a database server
 MySQL is ideal for both small and large applications
 MySQL supports standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use

What Can PHP Do?

 PHP can generate dynamic page content

Prepared By: Mahesh Manchanda Department of CS & IT 1


Graphic Era Hill University, Dehradun

 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and
even Flash movies. You can also output any text, such as XHTML and XML.

Why PHP?

 PHP runs on different platforms (Windows, Linux, Unix, etc.)


 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP is FREE to download from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:

 Install Apache (or IIS) on your own server, install PHP, and MySQL
 Or install wampserver.
 Or find a web hosting plan with PHP and MySQL support

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.

On servers with shorthand support enabled you can start a scripting block with <? and
end with ?>.

For maximum compatibility, we recommend that you use the standard form (<?php)
rather than the shorthand form.

<?php
?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP
scripting code.

Prepared By: Mahesh Manchanda Department of CS & IT 2


Graphic Era Hill University, Dehradun

Below, we have an example of a simple PHP script which sends the text "Hello World" to
the browser:

<html>
<body>

<?php
echo "Hello World ";
?>

</body>
</html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from another.

There are two basic statements to output text with PHP: echo and print. In the example
above we have used the echo statement to output the text "Hello World".

Note: The file must have a .php extension. If the file has a .html extension, the PHP code
will not be executed.

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment


block.

<html>
<body>

<?php
//This is a comment

/*
This is
a comment
block
*/
?>
</body>
</html> -

Prepared By: Mahesh Manchanda Department of CS & IT 3


Graphic Era Hill University, Dehradun

PHP Case Sensitivity


In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive.
In the example below, all three echo statements below are legal
(and equal):
Example

<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

Variables in PHP

Variables are used for storing a values, like text strings, numbers or
arrays.

When a variable is declared, it can be used over and over again in


your script.

All variables in PHP start with a $ sign symbol.


The correct way of declaring a variable in PHP:

$var_name = value;

Prepared By: Mahesh Manchanda Department of CS & IT 4


Graphic Era Hill University, Dehradun

New PHP programmers often forget the $ sign at the beginning of the variable. In that
case it will not work.

Let's try creating a variable containing a string, and a variable containing a number:

<?php
$txt="Hello World!";
$x=16;
?>

However; all variable names are case-sensitive.

In the example below, only the first statement will display the value of
the $color variable (this is because $color, $COLOR, and $coLOR are
treated as three different variables):

<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>

PHP is a Loosely Typed Language

In PHP, a variable does not need to be declared before adding a value to it.

In the example above, you see that you do not have to tell PHP which data type the
variable is.

Prepared By: Mahesh Manchanda Department of CS & IT 5


Graphic Era Hill University, Dehradun

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, you have to declare (define) the type and
name of the variable before using it.

In PHP, the variable is declared automatically when you use it.

Naming Rules for Variables

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the


variable
 A variable name must start with a letter or the underscore
character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two
different variables)

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

 local
 global
 static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:

Prepared By: Mahesh Manchanda Department of CS & IT 6


Graphic Era Hill University, Dehradun

Example
<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:

Example

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

PHP The global Keyword


The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

Prepared By: Mahesh Manchanda Department of CS & IT 7


Graphic Era Hill University, Dehradun

<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a further
job.

To do this, use the static keyword when you first declare the variable:

Example

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

Prepared By: Mahesh Manchanda Department of CS & IT 8


Graphic Era Hill University, Dehradun

PHP - Echo
As you saw in the above examples, the PHP command echo is a means of outputting text
to the web browser. Throughout your PHP career you will be using the echo command
more than any other.

Outputting a String
You can place either a string variable or you can use quotes, like we do below, to create a
string that the echo function will output.

PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>

Display:
Hello!

I love using PHP!

In the above example we output "Hello!" without a hitch. The text we are outputting is
being sent to the user in the form of a web page, so it is important that we use proper
HTML syntax!

In our second echo statement we use echo to write a valid Header 5 HTML statement. To
do this we simply put the <h5> at the beginning of the string and closed it at the end of
the string. Just because you're using PHP to make web pages does not mean you can
forget about HTML syntax!

Careful When Echoing Quotes!

It is pretty cool that you can output HTML with PHP. However, you must be careful
when using HTML code or any other string that includes quotes! Echo uses quotes to
define the beginning and end of the string, so you must use one of the following tactics if
your string contains quotations:

 Don't use quotes inside your string


 Escape your quotes that are within the string with a backslash. To escape a quote
just place a backslash directly before the quotation mark, i.e. \"

Prepared By: Mahesh Manchanda Department of CS & IT 9


Graphic Era Hill University, Dehradun

 Use single quotes (apostrophes) for quotes inside your string.

See our example below for the right and wrong use of echo:

PHP Code:

<?php
// This won't work because of the quotes around
specialH5!
echo "<h5 class="specialH5">I love using PHP!
</h5>";

// OK because we escaped the quotes!


echo "<h5 class=\"specialH5\">I love using PHP!
</h5>";

// OK because we used an apostrophe '


echo "<h5 class='specialH5'>I love using PHP!
</h5>";
?>

If you want to output a string that includes quotations, either use an apostrophe ( ' ) or
escape the quotations by placing a backslash in front of it ( \" ). The backslash will tell
PHP that you want the quotation to be used within the string and NOT to be used to end
echo's string.

Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the
common task of echoing all variables nearly foolproof! No quotations are required, even
if the variable does not hold a string. Below is the correct format for echoing a variable.

PHP Code:
<?php
$my_string = "Hello Mr. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Prepared By: Mahesh Manchanda Department of CS & IT 10


Graphic Era Hill University, Dehradun

Display:
Hello Mr. My name is: 4a

Echoing Variables and Text Strings


You can also place variables inside of double-quoted strings (e.g. "string here and a
$variable"). By putting a variable inside the quotes (" ") you are telling PHP that you
want it to grab the string value of that variable and use it in the string. The example below
shows an example of this cool feature.

PHP Code:
<?php
$my_string = "Hello Amit. My name is: ";
echo "$my_string Sachin <br />";
echo "Hi, I'm Amit. Who are you? $my_string <br />";
echo "Hi, I'm Amit. Who are you? $my_string Sachin";
?>

Display:
Hello Amit. My name is: Sachin
Hi, I'm Amit. Who are you? Hello Amit. My name is:
Hi, I'm Amit. Who are you? Hello Amit. My name is: Sachin

By placing variables inside a string you can save yourself some time and make your code
easier to read, though it does take some getting used to. Remember to use double-quotes,
single-quotes will not grab the value of the string. Single-quotes will just output the
variable name to the string, like )$my_string), rather than (Hello Amit. My name is: ).

PHP Operators

This section lists the different operators used in PHP.

Arithmetic Operators

Operator Description Example Result


+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20

Prepared By: Mahesh Manchanda Department of CS & IT 11


Graphic Era Hill University, Dehradun

x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division 5%2 1
remainder) 10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--

Assignment Operators

Operator Example Is The Same As


= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y

Comparison Operators

Operator Description Example


== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example


&& And x=6

Prepared By: Mahesh Manchanda Department of CS & IT 12


Graphic Era Hill University, Dehradun

y=3

(x < 10 && y > 1) returns true


|| Or x=6
y=3

(x==5 || y==5) returns false


! Not x=6
y=3

!(x==y) returns true

Conditional Statements

Very often when you write code, you want to perform different actions for different
decisions.

You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

 if statement - use this statement to execute some code only if


a specified condition is true
 if...else statement - use this statement to execute some code
if a condition is true and another code if the condition is false
 if...elseif....else statement - use this statement to select one
of several blocks of code to be executed
 switch statement - use this statement to select one of many
blocks of code to be executed

The if Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition) code to be executed if condition is true;

The following example will output "Have a nice weekend!" if the


current day is Friday:

<html>
<body>

Prepared By: Mahesh Manchanda Department of CS & IT 13


Graphic Era Hill University, Dehradun

<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

</body>
</html>

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code
only if the specified condition is true.

The if...else Statement

Use the if....else statement to execute some code if a condition is true and another code if
a condition is false.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>

</body>
</html>

Prepared By: Mahesh Manchanda Department of CS & IT 14


Graphic Era Hill University, Dehradun

If more than one line should be executed if a condition is true/false,


the lines should be enclosed within curly braces:

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>

</body>
</html>

The if...elseif....else Statement

Use the if....elseif...else statement to select one of several blocks of code to be executed.

Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a
nice day!":

Prepared By: Mahesh Manchanda Department of CS & IT 15


Graphic Era Hill University, Dehradun

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>

</body>
</html>

The PHP Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and
label2;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.

Prepared By: Mahesh Manchanda Department of CS & IT 16


Graphic Era Hill University, Dehradun

Example
<html>
<body>

<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>

</body>
</html>

PHP Loops

Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal lines in a script we can use loops to
perform a task like this.

In PHP, we have the following looping statements:

 while - loops through a block of code while a specified condition


is true
 do...while - loops through a block of code once, and then
repeats the loop as long as a specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an
array

The while Loop

The while loop executes a block of code while a condition is true.

Prepared By: Mahesh Manchanda Department of CS & IT 17


Graphic Era Hill University, Dehradun

Syntax
while (condition)
{
code to be executed;
}

Example

The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>

<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The do...while Statement

The do...while statement will always execute the block of code once, it will then check
the condition, and repeat the loop while the condition is true.

Syntax
do
{
code to be executed;
Prepared By: Mahesh Manchanda Department of CS & IT 18
Graphic Era Hill University, Dehradun

}
while (condition);

Example

The example below defines a loop that starts with i=1. It will then increment i with 1, and
write some output. Then the condition is checked, and the loop will continue to run as
long as i is less than, or equal to 5:

<html>
<body>

<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>

</body>
</html>

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax
for (init; condition; increment)
{
code to be executed;
}

Prepared By: Mahesh Manchanda Department of CS & IT 19


Graphic Era Hill University, Dehradun

Parameters:

 init: Mostly used to set a counter (but can be any code to be


executed once at the beginning of the loop)
 condition: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop
ends.
 increment: Mostly used to increment a counter (but can be any
code to be executed at the end of the loop)

Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).

Example

The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Prepared By: Mahesh Manchanda Department of CS & IT 20


Graphic Era Hill University, Dehradun

The foreach Loop

The foreach loop is used to loop through arrays.

Syntax
foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value (and
the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the
next array value.

Example

The following example demonstrates a loop that will print the values of the given array:

<html>
<body>

<?php
$x=array("one","two",3);
foreach ($x as $value)
{
echo $value . "<br />";
}
?>

</body>
</html>

Output:

One
two
three

Prepared By: Mahesh Manchanda Department of CS & IT 21


Graphic Era Hill University, Dehradun

PHP ARRAY

An array is a data structure that stores one or more similar type of


values in a single value. For example if you want to store 100 numbers
then instead of defining 100 variables its easy to define an array of 100
length.

There are three different kind of arrays and each array value is accessed
using an ID c 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 rather than in a
strict linear index order.
 Multidimensional array - An array containing one or more
arrays and values are accessed using multiple indices
You set up an array like this:

$list = array( );
First you type out what you want your array to be called ($list, in the array above) and,
after an equals sign, you type this:

array( );

So setting up an array just involves typing the word array followed by a pair of round
brackets. This is enough to tell PHP that you want to set up the array. But there's nothing
in the array yet. All we're doing with our line of code is telling PHP to set up an array,
and give it the name $list.

You can use two basic methods to put something into an array.

Method One – Type between the round brackets

Prepared By: Mahesh Manchanda Department of CS & IT 22


Graphic Era Hill University, Dehradun

The first method involves typing your values between the round brackets of array(). In
the code below, we're setting up an array to hold the seasons of the year:

$seasons = array( "Autumn", "Winter", "Spring", "Summer" );


So the name of the array is $seasons. Between the round brackets of array(), we have
typed some values. Each value is separated by a comma:

("Autumn", "Winter", "Spring", "Summer")

Arrays work by having a position, and some data for that position. In the above array,
"Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and
"Summer" is in position 3.

The first position is always zero, unless you tell PHP otherwise. But the position is know
as a Key. The Key then has a value attached to it. You can specify your own numbers for
the Keys. If so, you do it like this:

$seasons = array( 1 => "Autumn", 2 => "Winter", 3 =>


"Spring", 4 => "Summer" );
You can have numbers for the values of your keys. Here's an array that stores the
numbers 10, 20, 30 and 40.

$Array_Name = array(10, 20, 30, 40);

Because no keys were specified, PHP will set your array up like this:

0=> 10,
1=> 20,
2=> 30,
3=> 40

Here's the same array again, only this time we're specifying our own key:

$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
This array will then look like this:

1=> 10,
2=> 20,
3=> 30,
4=> 40

Prepared By: Mahesh Manchanda Department of CS & IT 23


Graphic Era Hill University, Dehradun

So the key name is typed before the => symbol, and the data stored under this key is to
the right.

You can store text and numbers in the same array:

$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");

Method two – Assign values to an array

Another way to put values into an array is like this:

$seasons = array();

$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";

Here, the array is first set up with $seasons = array();. This tells PHP that you want to
create an array with the name of $seasons. To store values in the array you first type the
name of the array, followed by a pair of square brackets:

$seasons[ ]

After the equals sign, you type out what you want to store in this position. Because no
numbers were typed in between the square brackets, PHP will assign the number 0 as the
first key:

0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"

This is exactly the same as the array you saw earlier. If you want different numbers for
your keys, then simply type them between the square brackets:

$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";

PHP will then see your array like this:

1=> "Autumn",
2=> "Winter",

Prepared By: Mahesh Manchanda Department of CS & IT 24


Graphic Era Hill University, Dehradun

3=> "Spring",
4=> "Summer"

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function
reference.

<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )


{
echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce following result:

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

Prepared By: Mahesh Manchanda Department of CS & IT 25


Graphic Era Hill University, Dehradun

Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so
that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our associative
array, and the value would be their respective salary.

NOTE: Don't keep associative array inside double quote while printing otheriwse it
would not return any value.

Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"Ayush" => 20000,
"Amit" => 10000,
"Sachin" => 5000
);

echo "Salary of Ayush is $salaries[Ayush] <br />";


echo "Salary of Amit is $salaries[Amit] <br />";
echo "Salary of Sachin is $salaries[Sachin] "<br
/>";

/* Second method to create array. */


$salaries['Ayush’] = "high";
$salaries['Amit'] = "medium";
$salaries['Sachin'] = "low";

Prepared By: Mahesh Manchanda Department of CS & IT 26


Graphic Era Hill University, Dehradun

echo "Salary of “Ayush” is ".


$salaries['“Ayush”'] . "<br />";
echo "Salary of Amit is ". $salaries['Amit']. "<br
/>";
echo "Salary of Sachin is ". $salaries['Sachin'].
"<br />";
?>
</body>
</html>

This will produce following result:

Salary of “Ayush” is 20000


Salary of Amit is 10000
Salary of Sachin is 5000
Salary of “Ayush” is high
Salary of Amit is medium
Salary of Sachin is low

Multidimensional Arrays
A multi-dimensional array each element in the main array can also
be an array. And each element in the sub-array can be an array, and
so on. Values in the multi-dimensional array are accessed using
multiple index.

$matrix = array(

array(5,5,5,5,),

array(6,6,6,6),

array(7,7,7,7)

)
Example
In this example we create a two dimensional array to store marks of three students in
three subjects:

Prepared By: Mahesh Manchanda Department of CS & IT 27


Graphic Era Hill University, Dehradun

This example is an associative array, you can create numeric array in the same fashion.

<html>
<body>
<?php
$marks = array(
"Ayush" => array("physics" => 35,"maths" => 30,

"chemistry" => 39),


"Amit" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"Sachin" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for “Ayush” in physics : " ;
echo $marks['“Ayush”']['physics'] . "<br />";
echo "Marks for Amit in maths : ";
echo $marks['Amit']['maths'] . "<br />";
echo "Marks for Sachin in chemistry : " ;
echo $marks['Sachin']['chemistry'] . "<br />";
?>
</body>
</html>

Physics Math Chemistry

35 39
Ayush
30
30 29
Amit 32
31 39
Sachin 22

This will produce following result:

Marks for “Ayush” in physics : 35


Marks for Amit in maths : 32
Marks for Sachin in chemistry :39

Prepared By: Mahesh Manchanda Department of CS & IT 28


Graphic Era Hill University, Dehradun

PHP Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and
returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you:

 Creating a PHP Function

 Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more
than 1000 of built-in library functions created for different area and you just need to call
them according to your requirement.

Creating PHP Function:


Its very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call it.
Following example creates a function called writeMessage() and then calls it just after
creating it.

Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below:

<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice
time!";

Prepared By: Mahesh Manchanda Department of CS & IT 29


Graphic Era Hill University, Dehradun

}
/* Calling a PHP Function */
writeMessage();

?>

</body>
</html>

This will display following result:

You are really a nice person, Have a nice time!

PHP Functions with Parameters:


PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function.
Following example takes two integer parameters and add them together and then print
them.

<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>

This will display following result:

Sum of the two numbers is : 30

Passing Arguments by Reference:

Prepared By: Mahesh Manchanda Department of CS & IT 30


Graphic Era Hill University, Dehradun

It is possible to pass arguments to functions by reference. This means that a reference to


the variable is manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the variable
name in either the function call or the function definition.

Following example depicts both the cases.

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}

function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>

This will display following result:

Original Value is 15
Original Value is 21

PHP Functions returning value:

Prepared By: Mahesh Manchanda Department of CS & IT 31


Graphic Era Hill University, Dehradun

A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from
a function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>

This will display following result:

Returned value from the function : 30

Setting Default Values for Function Parameters:


You can set a parameter to have a default value if the function's caller doesn't pass it.

Following function prints NULL in case use does not pass any value to this function.

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php

Prepared By: Mahesh Manchanda Department of CS & IT 32


Graphic Era Hill University, Dehradun

function printMe($param = “GEHU”)


{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>

This will produce following result:

This is test

Dynamic Function Calls:

It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself. Following example
depicts this behaviour.

<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>

This will display following result:

Hello

Prepared By: Mahesh Manchanda Department of CS & IT 33


Graphic Era Hill University, Dehradun

PHP Forms and User Input

The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.

PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any
form element in an HTML page will automatically be available to your PHP scripts.

Example

The example below contains an HTML form with two input fields and a submit button:

<html>
<body>

<form action="http://localhost/CS/welcome.php"
method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>

When a user fills out the form above and click on the submit button, the form data is sent
to a PHP file, called "welcome.php":

"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>!<br />


You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

Output could be something like this:

Welcome John!
You are 28 years old.

Prepared By: Mahesh Manchanda Department of CS & IT 34


Graphic Era Hill University, Dehradun

Form Validation

User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and reduces the server load.

You should consider server validation if the user input will be inserted into a database. A
good way to validate a form on the server is to post the form to itself, instead of jumping
to a different page. The user will then get the error messages on the same page as the
form. This makes it easier to discover the error.

PHP $_GET

The built-in $_GET function is used to collect values in a form with method="get".

The $_GET Function

The built-in $_GET function is used to collect values from a form sent with
method="get".

Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar) and has limits on the amount of information to
send (max. 200 characters).

Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the "Submit" button, the URL sent to the server could look
something like this:

http:/localhost/welcome.php?fname=Peter&age=37

The "welcome.php" file can now use the $_GET function to collect form data (the names
of the form fields will automatically be the keys in the $_GET array):

Welcome <?php echo $_GET["fname"]; ?>.<br />


You are <?php echo $_GET["age"]; ?> years old!

GET vs. POST

Prepared By: Mahesh Manchanda Department of CS & IT 35


Graphic Era Hill University, Dehradun

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3
=> value3, ...)). This array holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them
from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use method="get"?

When using method="get" in HTML forms, all variable names and values are displayed
in the URL.

Note: This method should not be used when sending passwords or other sensitive
information!

However, because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.

Note: The get method is not suitable for large variable values; the value cannot exceed
200 characters.

PHP $_POST Function

The built-in $_POST function is used to collect values in a form with method="post".

The $_POST Function

The built-in $_POST function is used to collect values from a form sent with
method="post".

Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.

Note: However, there is an 8 Mb max size for the POST method, by default (can be
changed by setting the post_max_size in the php.ini file).

Example
<form action="welcome.php" method="post">

Prepared By: Mahesh Manchanda Department of CS & IT 36


Graphic Era Hill University, Dehradun

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


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

When the user clicks the "Submit" button, the URL will look like this:

http://localhost/GEHU/welcome.php

The "welcome.php" file can now use the $_POST function to collect
form data (the names of the form fields will automatically be the keys
in the $_POST array):

Welcome <?php echo $_POST["fname"]; ?>!<br />


You are <?php echo $_POST["age"]; ?> years old.

When to use method="post"?

Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.

However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.

The PHP $_REQUEST Function

The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST,
and $_COOKIE.

The $_REQUEST function can be used to collect form data sent with both the GET and
POST methods.

Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.

PHP Form Validation


The HTML form we will be working at in the below example, contains various input
fields: required and optional text fields, radio buttons, and a submit button:
Prepared By: Mahesh Manchanda Department of CS & IT 37
Graphic Era Hill University, Dehradun

The validation rules for the form above are as follows:

Field Validation Rules


Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

First we will look at the plain HTML code for the form:

The HTML code of the above screenshot is looks like this:

<!DOCTYPE HTML>

Prepared By: Mahesh Manchanda Department of CS & IT 38


Graphic Era Hill University, Dehradun

<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
Prepared By: Mahesh Manchanda Department of CS & IT 39
Graphic Era Hill University, Dehradun

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]/>script> location.href=
“www.mywebsite.com” </script> );?>">
Name: <input type="text" name="name" value="<?php echo $name;?
>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>

Prepared By: Mahesh Manchanda Department of CS & IT 40


Graphic Era Hill University, Dehradun

Website: <input type="text" name="website" value="<?php echo


$website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?
></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female")
echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male")
echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself,
instead of jumping to a different page. This way, the user will get error messages on the
same page as the form.

Prepared By: Mahesh Manchanda Department of CS & IT 41


Graphic Era Hill University, Dehradun

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to


HTML entities. This means that it will replace HTML characters
like < and > with &lt; and &gt;. This prevents attackers from
exploiting the code by injecting HTML or Javascript code (Cross-
site Scripting attacks) in forms.

PHP Form Security

The $_SERVER["PHP_SELF"] variable can be used by hackers!

If PHP_SELF is used in your page then a user can enter a slash (/) and
then some Cross Site Scripting (XSS) commands to execute.
Cross-site scripting (XSS) is a type of computer security vulnerability typically
found in Web applications. XSS enables attackers to inject client-side script into
Web pages viewed by other users.

Assume we have the following form in a page named "test_form.php":

<form method="post" action="<?php echo


$_SERVER["PHP_SELF"];?>">

Now, if a user enters the normal URL in the address bar like
"http://localhost/test_form.php", the above code will be translated
to:

<form method="post" action="test_form.php">


So far, so good.

However, consider that a user enters the following URL in the address bar:

http://localhost/test_form.php/%22%3E%3Cscript
%3Ealert('hacked')%3C/script%3E
In this case, the above code will be translated to:

Prepared By: Mahesh Manchanda Department of CS & IT 42


Graphic Era Hill University, Dehradun

<form method="post"
action="test_form.php/"><script>alert('hacked')</script>

This code adds a script tag and an alert command. And when the page loads, the
JavaScript code will be executed (the user will see an alert box). This is just a simple and
harmless example how the PHP_SELF variable can be exploited.

Be aware of that any JavaScript code can be added inside the <script> tag! A hacker
can redirect the user to a file on another server, and that file can hold malicious code that
can alter the global variables or submit the form to another address to save the user data,
for example.

<script>location.href('http://www.hacked.com')</script>

How To Avoid $_SERVER["PHP_SELF"] Exploits?

$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars()


function.

The form code should look like this:

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">

The htmlspecialchars() function converts special characters to HTML entities. Now if the
user tries to exploit the PHP_SELF variable, it will result in the following output:

<form method="post"
action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

The exploit attempt fails, and no harm is done!

The first thing we will do is to pass all variables through PHP's htmlspecialchars()
function.

When we use the htmlspecialchars() function; then if a user tries to submit the following
in a text field:

<script>location.href('http://www.hacked.com')</script>

Prepared By: Mahesh Manchanda Department of CS & IT 43


Graphic Era Hill University, Dehradun

this would not be executed, because it would be saved as HTML escaped code, like this:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

1. Strip unnecessary characters (extra space, tab, newline) from the user input data
(with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)

The next step is to create a function that will do all the checking for us (which is much
more convenient than writing the same code over and over again).

We will name the function test_input().

Now, we can check each $_POST variable with the test_input() function, and the script
looks like this:

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

In the abovecode we have added some new variables: $nameErr, $emailErr, $genderErr,
and $websiteErr. These error variables will hold error messages for the required fields.
We have also added an if else statement for each $_POST variable. This checks if the
$_POST variable is empty (with the PHP empty() function). If it is empty, an error

Prepared By: Mahesh Manchanda Department of CS & IT 44


Graphic Era Hill University, Dehradun

message is stored in the different error variables, and if it is not empty, it sends the user
input data through the test_input() function:

Display The Error Messages

Then in the HTML form, we add a little script after each required field, which generates
the correct error message if needed (that is if the user tries to submit the form without
filling out the required fields):

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">

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


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5"
cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>

The next step is to validate the input data, that is "Does the Name field contain only
letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".

Validate Name

The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:

Prepared By: Mahesh Manchanda Department of CS & IT 45


Graphic Era Hill University, Dehradun

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.

Validate E-mail

The easiest and safest way to check whether an email address is well-formed is to use
PHP's filter_var() function.

In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";

Validate URL

The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then
store an error message:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

Server Side Includes (SSI)

You can insert the content of one PHP file into another PHP file before
the server executes it, with the include() or require() function.

The two functions are identical in every way, except how they handle errors:

Prepared By: Mahesh Manchanda Department of CS & IT 46


Graphic Era Hill University, Dehradun

 include() generates a warning, but the script will


continue execution
 require() generates a fatal error, and the script will
stop

These two functions are used to create functions, headers, footers, or elements that will
be reused on multiple pages.

Server side includes saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. When the header needs to be updated,
you can only update the include file, or when you add a new page to your site, you can
simply change the menu file (instead of updating the links on all your web pages).

PHP include() Function

The include() function takes all the content in a specified file and includes it in the
current file.

If an error occurs, the include() function generates a warning, but the script will continue
execution.

Example 1

Assume that you have a standard header file, called "header.php". To include the header
file in a page, use the include() function:

<html>
<body>

<?php
include("menu.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
Prepared By: Mahesh Manchanda Department of CS & IT 47
Graphic Era Hill University, Dehradun

</html>

Example 2

Assume we have a standard menu file, called "menu.php", that should be used on all
pages:

<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>

All pages in the Web site should include this menu file. Here is how it
can be done:

<html>
<body>

<?php include("menu.php"); ?>

<h1>Welcome to my home page.</h1>


<p>Some text.</p>

</body>
</html>

If you look at the source code of the page above (in a browser), it will
look like this:

<html>
<body>

<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>

Prepared By: Mahesh Manchanda Department of CS & IT 48


Graphic Era Hill University, Dehradun

<h1>Welcome to my home page!</h1>


<p>Some text.</p>

</body>
</html>

PHP require() Function

The require() function is identical to include(), except that it handles errors differently.

If an error occurs, the include() function generates a warning, but the script will
continue execution. The require() generates a fatal error, and the script will stop.

Error Example include() Function


<html>
<body>

<?php
include("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: include(wrongFile.php) [function.include]:


failed to open stream:
No such file or directory in C:\home\website\test.php on
line 5

Warning: include() [function.include]:


Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

Hello World!

Notice that the echo statement is executed! This is because a Warning does not stop the
script execution.

Prepared By: Mahesh Manchanda Department of CS & IT 49


Graphic Era Hill University, Dehradun

Error Example require() Function

Now, let's run the same example with the require() function.

<html>
<body>

<?php
require("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: require(wrongFile.php) [function.require]:


failed to open stream:
No such file or directory in C:\home\website\test.php on
line 5

Fatal error: require() [function.require]:


Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

The echo statement is not executed, because the script execution stopped after the fatal
error.

It is recommended to use the require() function instead of include(), because scripts


should not continue after an error.

Prepared By: Mahesh Manchanda Department of CS & IT 50


Graphic Era Hill University, Dehradun

PHP STRING

They are sequences of characters, like "PHP supports string operations".

Following are valid examples of string

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>

This will produce following result:

My $variable will not print!\n


My name will print

There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP:

 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their
values.

The escape-sequence replacements are:

 \n is replaced by the newline character

Prepared By: Mahesh Manchanda Department of CS & IT 51


Graphic Era Hill University, Dehradun

 \r is replaced by the carriage-return character


 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator:

<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>

This will produce following result:

Hello World 1234

If we look at the code above you see that we used the concatenation operator two times.
This is because we had to insert a third string.

Between the two string variables we added a string with a single character, an empty
space, to separate the two variables.

Using the strlen() function

The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!":

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

This will produce following result:

12

The length of a string is often used in loops or other functions, when it is important to
know when the string ends. (i.e. in a loop, we would want to stop the loop after the last
character in the string)

Using the strpos() function

Prepared By: Mahesh Manchanda Department of CS & IT 52


Graphic Era Hill University, Dehradun

The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If
no match is found, it will return FALSE.

Let's see if we can find the string "world" in our string:

<?php
echo strpos("Hello world!","world");
?>

This will produce following result:

As you see the position of the string "world" in our string is position 6. The reason that it
is 6, and not 7, is that the first position in the string is 0, and not 1.

chr

chr — Return a specific character

$ascii = 65
echo chr ( $ascii )
OUTPUT
A

ord — Return ASCII value of character

$string = “A”
Echo ord ( string $string )
OUTPUT
65

chr — Return a specific character

fprintf — Write a formatted string to a stream

ltrim — Strip whitespace (or other characters) from the beginning of a string

ord — Return ASCII value of character

print — Output a string

printf — Output a formatted string

Prepared By: Mahesh Manchanda Department of CS & IT 53


Graphic Era Hill University, Dehradun

rtrim — Strip whitespace (or other characters) from the end of a string

similar_text — Calculate the similarity between two strings

str_repeat — Repeat a string

str_replace — Replace all occurrences of the search string with the replacement string

str_split — Convert a string to an array

str_word_count — Return information about words used in a string

strcasecmp — Binary safe case-insensitive string comparison

strcmp — Binary safe string comparison

stripos — Find the position of the first occurrence of a case-insensitive substring in a


string

strlen — Get string length

strnatcasecmp — Case insensitive string comparisons using a "natural order"


algorithm

strncmp — Binary safe string comparison of the first n characters

strpos — Find the position of the first occurrence of a substring in a string

strrchr — Find the last occurrence of a character in a string

strrev — Reverse a string

string

strrpos — Find the position of the last occurrence of a substring in a string

strstr — Find the first occurrence of a string

strtolower — Make a string lowercase

strtoupper — Make a string uppercase

substr_count — Count the number of substring occurrences

trim — Strip whitespace (or other characters) from the beginning and end of a string

Prepared By: Mahesh Manchanda Department of CS & IT 54


Graphic Era Hill University, Dehradun

ucwords — Uppercase the first character of each word in a string

vsprintf — Return a formatted string

PHP Date() Function

The PHP date() function is used to format a time and/or date.

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

A timestamp is a sequence of characters, denoting the date and/or time at which a


certain event occurred.

Syntax
date(format,timestamp)

Parameter Description
Format Required. Specifies the format of the timestamp
Timestamp Optional. Specifies a timestamp. Default is the current date and time

PHP Date() - Format the Date

The required format parameter in the date() function specifies how to format the
date/time.

Here are some characters that can be used:

 d - Represents the day of the month (01 to 31)


 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)

A list of all the characters that can be used in the format parameter is listed below:

Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:

<?php
echo date("Y/m/d", ) . "<br />";

Prepared By: Mahesh Manchanda Department of CS & IT 55


Graphic Era Hill University, Dehradun

echo date("Y.m.d") . "<br />";


echo date("Y-m-d")
?>

The output of the code above could be something like this:

2014/05/12
2014.05.12
2014-05-12

PHP Date() - Adding a Timestamp

The optional timestamp parameter in the date() function specifies a timestamp. If you do
not specify a timestamp, the current date and time will be used.

The mktime() function returns the Unix timestamp for a date.

The Unix timestamp contains the number of seconds between the Unix time (January 1
1970 00:00:00 GMT) and the time specified.

Syntax for mktime()


mktime(hour,minute,second,month,day,year,is_dst)

To go one day in the future we simply add one to the day argument of mktime():

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>

The output of the code above could be something like this:

Tomorrow is 20014/6/05

Dates are so much part of everyday life that it becomes easy to work with them without
thinking. PHP also provides powerful tools for date arithmetic that make manipulating
dates easy.

Getting the Time Stamp with time():

Prepared By: Mahesh Manchanda Department of CS & IT 56


Graphic Era Hill University, Dehradun

PHP's time() function gives you all the information that you need about the current date
and time. It requires no arguments but returns an integer.

The integer returned by time() represents the number of seconds elapsed since midnight
GMT on January 1, 1970. This moment is known as the UNIX time, and the number of
seconds that have elapsed since then is referred to as a time stamp.

<?php
//print time();
Echo time();
?>

It will produce following result:

948316201

This is something difficult to understand. But PHP offers excellent tools to convert a time
stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate():

The function getdate() optionally accepts a time stamp and returns an


associative array containing information about the date. If you omit the
time stamp, it works with the current time stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().

Key Description Example

Seconds Seconds past the minutes (0-59) 20

Minutes Minutes past the hour (0 - 59) 29

Hours Hours of the day (0 - 23) 22

Mday Day of the month (1 - 31) 11

Wday Day of the week (0 - 6) 4

Mon Month of the year (1 - 12) 7

Year Year (4 digits) 1997

Yday Day of year ( 0 - 365 ) 19

Prepared By: Mahesh Manchanda Department of CS & IT 57


Graphic Era Hill University, Dehradun

weekday Day of the week Thursday

Month Month of the year January

0 Timestamp 948370048

Now you have complete control over date and time. You can format this date and time in
whatever format you want.

Example:

Try out following example

<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
print "$key = $val<br />";
}
$formated_date = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];

print $formated_date;
?>

It will produce following result:

seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007

Converting a Time Stamp with date():

Prepared By: Mahesh Manchanda Department of CS & IT 58


Graphic Era Hill University, Dehradun

The date() function returns a formatted string representing a date. You can exercise an
enormous amount of control over the format that date() returns with a string argument
that you must pass to it.

date(format,timestamp)

The date() optionally accepts a time stamp if omitted then current date and time will be
used. Any other data you include in the format string passed to date() will be included in
the return value.

Following table lists the codes that a format string can contain:

Format Description Example

A 'am' or 'pm' lowercase Pm

A 'AM' or 'PM' uppercase PM

D Day of month, a number with leading zeroes 20

D Day of week (three letters) Thu

F Month name January

H Hour (12-hour format - leading zeroes) 12

H Hour (24-hour format - leading zeroes) 22

G Hour (12-hour format - no leading zeroes) 12

G Hour (24-hour format - no leading zeroes) 22

I Minutes ( 0 - 59 ) 23

J Day of the month (no leading zeroes 20

l (Lower 'L') Day of the week Thursday

L Leap year ('1' for yes, '0' for no) 1

M Month of year (number - leading zeroes) 1

M Month of year (three letters) Jan

N Month of year (number - no leading zeroes) 2

S Seconds of hour 20

U Time stamp 948372444

Prepared By: Mahesh Manchanda Department of CS & IT 59


Graphic Era Hill University, Dehradun

Y Year (two digits) 06

Y Year (four digits) 2006

Z Day of year (0 - 365) 206

Z Offset in seconds from GMT +5

Example:

Try out following example

<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \t g.i a", time());
?>

It will produce following result:

05/12/14 16.27:55
Today is 12 of May 2014, 4.27 pm

PHP Superglobals

PHP provides a large number of predefined variables to any script which it


runs.PHP provides an additional set of predefined arrays containing
variables from the web server the environment, and user input. These new
arrays are called superglobals:

All the following variables are automatically available in every scope.

Variable Description

Contains a reference to every variable which is currently available within


$GLOBALS the global scope of the script. The keys of this array are the names of the
global variables.

Prepared By: Mahesh Manchanda Department of CS & IT 60


Graphic Era Hill University, Dehradun

This is an array containing information such as headers, paths, and script


locations. The entries in this array are created by the web server. There is
$_SERVER
no guarantee that every web server will provide any of these. See next
section for a complete list of all the SERVER variables.

An associative array of variables passed to the current script via the


$_GET
HTTP GET method.

An associative array of variables passed to the current script via the


$_POST
HTTP POST method.

An associative array of items uploaded to the current script via the HTTP
$_FILES
POST method.

An associative array consisting of the contents of $_GET, $_POST, and


$_REQUEST
$_COOKIE.

An associative array of variables passed to the current script via HTTP


$_COOKIE
cookies.

An associative array containing session variables available to the current


$_SESSION
script.

$_PHP_SELF A string containing PHP script file name in which it is called.

Server variables: $_SERVER

$_SERVER is an array containing information such as headers, paths, and script


locations. The entries in this array are created by the web server. There is no guarantee
that every web server will provide any of these.

Variable Description

The filename of the currently executing


$_SERVER['PHP_SELF']
script, relative to the document root

Array of arguments passed to the script.


When the script is run on the command
line, this gives C-style access to the
$_SERVER['argv']
command line parameters. When called
via the GET method, this will contain the
query string.

Contains the number of command line


$_SERVER['argc'] parameters passed to the script if run on
the command line.

Prepared By: Mahesh Manchanda Department of CS & IT 61


Graphic Era Hill University, Dehradun

What revision of the CGI specification


$_SERVER['GATEWAY_INTERFACE']
the server is using; i.e. 'CGI/1.1'.

The IP address of the server under which


$_SERVER['SERVER_ADDR']
the current script is executing.

The name of the server host under which


the current script is executing. If the
$_SERVER['SERVER_NAME'] script is running on a virtual host, this
will be the value defined for that virtual
host.

Name and revision of the information


$_SERVER['SERVER_PROTOCOL'] protocol via which the page was
requested; i.e. 'HTTP/1.0';

Which request method was used to


$_SERVER['REQUEST_METHOD'] access the page; i.e. 'GET', 'HEAD',
'POST', 'PUT'.

The timestamp of the start of the request.


$_SERVER['REQUEST_TIME']
Available since PHP 5.1.0.

The query string, if any, via which the


$_SERVER['QUERY_STRING']
page was accessed.

The absolute pathname of the currently


$_SERVER['SCRIPT_FILENAME']
executing script.

The port on the server machine being


used by the web server for
$_SERVER['SERVER_PORT']
communication. For default setups, this
will be '80'.

ADVANCE PHP

PHP File Upload

With PHP, it is possible to upload files to the server.

Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads.


Prepared By: Mahesh Manchanda Department of CS & IT 62
Graphic Era Hill University, Dehradun

In your "php.ini" file, search for the file_uploads directive, and set it to
On:
file_uploads = On

Create an Upload-File Form

To allow users to upload files from a form can be very useful. Look at the following
HTML form for uploading files:

<!DOCTYPE html>
<html>
<body>

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


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above:

 Make sure that the form uses method="post"


 The form also needs the following attribute: enctype="multipart/form-data". It
specifies which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:

 The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control

The form above sends data to a file called "upload.php", which we will create next.

Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:

<?php

Prepared By: Mahesh Manchanda Department of CS & IT 63


Graphic Era Hill University, Dehradun

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

By using the global PHP $_FILES array you can upload files from a client computer
to the remote server.

The first parameter is the form's input name and the second index can be either
"name", "type", "size", "tmp_name" or "error". Like this:

 $_FILES["txtfile"]["name"] - the name of the uploaded file


 $_FILES["txtfile"]["type"] - the type of the uploaded file
 $_FILES["txtfile"]["size"] - the size in bytes of the uploaded file
 $_FILES["txtfile"]["tmp_name"] - the name of the temporary
copy of the file stored on the server
 $_FILES["file"]["error"] - the error code resulting from the file
upload

PHP script explained:

 $target_dir = "uploads/" - specifies the directory where the file is going to be


placed
 $target_file specifies the path of the file to be uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the file
 Next, check if the image file is an actual image or a fake image

Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.

Check if File Already Exists

Prepared By: Mahesh Manchanda Department of CS & IT 64


Graphic Era Hill University, Dehradun

Now we can add some restrictions.

First, we will check if the file already exists in the "uploads" folder. If it does, an error
message is displayed, and $uploadOk is set to 0:

Limit File Size

The file input field in our HTML form above is named "fileToUpload".

Now, we want to check the size of the file. If the file is larger than 500kb, an error
message is displayed, and $uploadOk is set to 0:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

Limit File Type

The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other
file types gives an error message before setting $uploadOk to 0:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

Complete Upload File PHP Script

The complete "upload.php" file now looks like this:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {

Prepared By: Mahesh Manchanda Department of CS & IT 65


Graphic Era Hill University, Dehradun

echo "File is not an image.";


$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder
on the server.

The temporary copied files disappears when the script ends. To store the uploaded file we
need to copy it to a different location:

<?php
if ((($_FILES["file"]["type"] == "image/gif")

Prepared By: Mahesh Manchanda Department of CS & IT 66


Graphic Era Hill University, Dehradun

|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg"))
&& ($_FILES["file"]["size"] < 20000))
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("c:/wamp/www/CS/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>

The script above checks if the file already exists, if it does not, it copies the file to the
specified folder.

Note: This example saves the file to a new folder called "upload"

PHP Cookies
A cookie is often used to identify a user.

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small


file that the server embeds on the user's computer. Each time
the same computer requests a page with a browser, it will send
the cookie too. With PHP, you can both create and retrieve
cookie values.
Prepared By: Mahesh Manchanda Department of CS & IT 67
Graphic Era Hill University, Dehradun

Cookies are often used to perform following tasks:

 Session management: Cookies are widely used to


manage user sessions. For example, when you use an
online shopping cart, you keep adding items in the cart
and finally when you checkout, all of those items are
added in the list of items you have purchased. This can
be achieved using cookies.

 User identification: Once a user visits a webpage, using
cookies, that user can be remembered. And later on,
depending upon the search/visit pattern of the user,
content which the user likely to be visited are served. A
good example of this is 'Retargetting'. A concept used in
online marketing, where depending upon the user's choice
of content, advertisements of relevant product, which the
user may buy, are served.

 Tracking / Analytics: Cookies are used to track the
user. Which, in turn, is used to analyze and serve
various kind of data of great value, like location,
technologies (e.g. browser, OS) form where the user
visited, how long (s)he stayed on various pages etc.

How to Create a Cookie?

Cookies are usually set in an HTTP header:

PHP provided setcookie() function to set a cookie. This function requires upto
six arguments and should be called before <html> tag. For each cookie this function has
to be called separately.

Prepared By: Mahesh Manchanda Department of CS & IT 68


Graphic Era Hill University, Dehradun

Syntax
setcookie(name, value, expire, path, domain, secure, httponl
y)
Parameters

setcookie() has several parameters. Following table discusses those.

Which type
Parameter Description
of data
name Name of the cookie. String
value Value of the cookie, stored in clients computer. String
Unix timestamp, i.e. number of seconds since January 1st, 1970
expire Integer
(called as Unix Epoch).
path Server path in which the cookie will be available. String
domain To which domain the cookie is available. String
secure If set true, the cookie is available over secure connection only. Boolean
If set true, the cookie is available over HTTP protocol only.
httponly Scripting languages like JavaScript won't be able to access the
cookie.

setcookie() returns boolean.

Example 1 Cookie

<?php
$username = 'Ankit';
setcookie('userid', $username);
?>

In the example above, we will create a cookie named "userid" and assign the value
"Ankit" to it.

As this cookie does not have an expiry time, then the cookie will be deleted once the user
closes their browser. This can be very useful for keeping a user logged in for an indefinite
amount of time, however, as soon as they close their browser (hence, have left the site),
the cookie is removed.

Prepared By: Mahesh Manchanda Department of CS & IT 69


Graphic Era Hill University, Dehradun

There are two very important things to abide by when using cookies. Firstly, there are
can be no HTML, text or white-space output before calling the setcookie() function. This
is due to a 'protocol restriction' and you will find that header() and session_start()
functions must also follow this rule.

Note: The value of the cookie is automatically URLencoded when sending the cookie,
and automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).

Note: The setcookie() function must appear BEFORE the <html> tag.

Accessing the Cookie


<?php
/* Prints the value stored in the username cookie */
echo $_COOKIE['userid'];

?>

This code uses the $_COOKIE superglobal to access any cookies set in the current
domain. If we were to run this script, it would output Ankit

You can use isset() function to check if a cookie is set or not.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["userid"]))
echo "Page Visited" . $_COOKIE["userid"] +1 ;
else
Prepared By: Mahesh Manchanda Department of CS & IT 70
Graphic Era Hill University, Dehradun

echo "Sorry... Not recognized" . "<br />";


?>
</body>

</html>

You can also set the expiration time of the cookie in another way. It may be easier than
using seconds.

Example 2

<?php
$expire=time()+60*60*24*30;
setcookie("userid", "Ankit", $expire);
?>

<html>
.....

In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours *
30 days).

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie("userid", "ankit", time()-3600);
?>

Practical Example of Cookies:

User Logon

Prepared By: Mahesh Manchanda Department of CS & IT 71


Graphic Era Hill University, Dehradun

 To give a more detailed look into how to use cookies, I am going to show you how to
create a little login form so that you can store the username and password in a cookie.

 We will use more complicated cookies now so that you can learn the full use of
setcookie().

Login.html
<html>
<head>
<title>User Logon</title>
</head>
<body>
<h2>User Login </h2>
<form name="login" method="post"
action="http://localhost/cs/login.php">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
Remember Me: <input type="checkbox" name="rememberme"
value="1"><br>
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>

Output

Prepared By: Mahesh Manchanda Department of CS & IT 72


Graphic Era Hill University, Dehradun

Now that we have our form, we will create our login script. We must decide what
restrictions we are going to place on the cookie.

I have decided that this will only run on the www.example.com domain and in the
/account directory only. Hence,

Login.php

<?php
/* These are our valid username and passwords */
$user = 'Ankit';
$pass = 'Ankit123';
if (isset($_POST['username']) && isset($_POST['password'))
{
if (($_POST['username'] == $user) && ($_POST['password'] == $pass))
{
if (isset($_POST['rememberme']))
{
/* Set cookie to last 1 year */
setcookie('username', $_POST['username'], time()+60*60*24*365, '/account', '
www.example.com');
setcookie('password', md5($_POST['password']), time()+60*60*24*365,
'/account', 'www.example.com');
}
else
{
/* Cookie expires when browser closes *
setcookie('username', $_POST['username'], false, '/account',
'www.example.com');
setcookie('password', md5($_POST['password']), false, '/account',
'www.example.com');
}
header('Location: index.php');
}
else
{
echo 'Username/Password Invalid';
}
}
else
{
echo 'You must supply a username and password.';
}

Prepared By: Mahesh Manchanda Department of CS & IT 73


Graphic Era Hill University, Dehradun

?>

Validating the data:


Login.php
<?php
/* These are our valid username and passwords */
$user = 'Ankit';
$pass = 'Ankit123';
if (isset($_COOKIE[['username']) && isset($_COOKIE['password'))
{
if (($_POST['username'] != $user) || ($_POST['password'] != md5($pass)))
{
header('Location: login.html');
}
else
{
echo 'Welcome back ' . $_COOKIE['username'];
}
}
else
{
header('Location: login.html');
}

?>

Explanations:
In this script, we just check that the cookie exists and is valid. If they aren't, then the
user is redirected back to the login form.

Otherwise a welcome message is included. The only important thing to notice is how we
have validated the password. Before on the login.php script, we have encrypted our
password using md5() and as this encryption cannot be undone,

we must compare encrypted versions. Hence, we encrypt our preset value and compare
it to the already hashed cookie value. This way, there is no chance of the original
password becoming available.

Prepared By: Mahesh Manchanda Department of CS & IT 74


Graphic Era Hill University, Dehradun

PHP Sessions

An alternative way to make data accessible across the


various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the


server where registered session variables and their values
are stored. This data will be available to all pages on the
site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path. For using any session variable make sure you have setup this path.
When a session is started following things happen:

PHP first creates a unique identifier for that particular session which is a random string
of 32 hexadecimal numbers such.

A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.

A PHP session variable is used to store information about, or change settings for a user
session. Session variables hold information about one single user, and are available to all
pages in one application.

A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP
automatically gets the unique session identifier string from the PHPSESSID cookie and
then looks in its temporary directory for the file bearing that name and a validation can
be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes
duration.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This


function first checks if a session is already started and if none is started then it starts

Prepared By: Mahesh Manchanda Department of CS & IT 75


Graphic Era Hill University, Dehradun

one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables
can be accessed during lifetime of a session.

The following example starts a session then register a variable called counter that is
incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result:

<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>

<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
Prepared By: Mahesh Manchanda Department of CS & IT 76
Graphic Era Hill University, Dehradun

<?php echo ( $msg ); ?>


</body>
</html>

Destroying a PHP Session:

A PHP session can be destroyed by session_destroy() function. This function does not
need any argument and a single call can destroy all the session variables. If you want to
destroy a single session variable then you can use unset() function to unset a session
variable.

Here is the example to unset a single variable:

<?php
unset($_SESSION['counter']);
?>

Here is the call which will destroy all the session variables:

<?php
session_destroy();
?>

Turning on Auto Session:


You don't need to call start_session() function to start a session when a user visits your
site if you can set session.auto_start variable to 1 in php.ini file.

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

Session variables hold information about one single user, and are available to all
pages in one application.

Sessions work by creating a unique id (UID) for each visitor and store variables based on
this UID. The UID is either stored in a cookie or is propagated in the URL.

PHP Sending E-mails

PHP allows you to send e-mails directly from a script.

The PHP mail() Function

Prepared By: Mahesh Manchanda Department of CS & IT 77


Graphic Era Hill University, Dehradun

The PHP mail() function is used to send emails from inside a script.

Syntax

mail(to,subject,message,headers,parameters)

Parameter Description
To Required. Spe1cifies the receiver / receivers of the email
Subject Required. Specifies the subject of the email. Note: This parameter
cannot contain any newline characters
Message Required. Defines the message to be sent. Each line should be separated
with a LF (\n). Lines should not exceed 70 characters
Headers Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n)
Parameters Optional. Specifies an additional parameter to the sendmail program

Note: For the mail functions to be available, PHP requires an installed and working email
system. The program to be used is defined by the configuration settings in the php.ini file.

PHP Simple E-Mail

The simplest way to send an email with PHP is to send a text email.

In the example below we first declare the variables ($to, $subject, $message, $from,
$headers), then we use the variables in the mail() function to send an e-mail:

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>

PHP Mail Form

With PHP, you can create a feedback-form on your website. The example below sends a
text message to a specified e-mail address:

<html>
<body>

Prepared By: Mahesh Manchanda Department of CS & IT 78


Graphic Era Hill University, Dehradun

<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>

</body>
</html>

This is how the example above works:


 First, check if the email input field is filled out
 If it is not set (like when the page is first visited); output the HTML form
 If it is set (after the form is filled out); send the email from the form
 When submit is pressed after the form is filled out, the page reloads, sees that the
email input is set, and sends the email

Prepared By: Mahesh Manchanda Department of CS & IT 79

S-ar putea să vă placă și