Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

PHP Tutorial

The document provides an introduction to PHP including what PHP is, why use PHP, PHP syntax, writing a first PHP program, server side includes in PHP, PHP variables, operators in PHP, and boolean operators in PHP. Key points covered include that PHP is a widely used server-side scripting language, it can be used freely with Apache web server, the basic structure of a PHP program embedded in HTML, and an overview of variables, operators, and logic in PHP programs.

Uploaded by

Raymund
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

PHP Tutorial

The document provides an introduction to PHP including what PHP is, why use PHP, PHP syntax, writing a first PHP program, server side includes in PHP, PHP variables, operators in PHP, and boolean operators in PHP. Key points covered include that PHP is a widely used server-side scripting language, it can be used freely with Apache web server, the basic structure of a PHP program embedded in HTML, and an overview of variables, operators, and logic in PHP programs.

Uploaded by

Raymund
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction to PHP

PHP: An Introduction

PHP is the most widely used server side scripting language. The most popular PHP
server 'Apache' is an open source server, and it comes bundled with Linux. Due to
this, one does not need to spend anything to be able to use PHP.
Why PHP?

• PHP has a very strong community and several websites available on internet
offering resources on PHP. Most of these resources come for free! Apart from
this the PHP is a very powerful scripting language.
• PHP supports almost all available famous databases so you do not need to
worry whether it will work with a particular database or not.
• For other benefits of PHP and to know what PHP can do you can visit
http://in2.php.net/manual/en/intro-whatcando.php

PHP Syntax
You can code PHP in any text editor including Notepad on Windows.

• The PHP code begins with <?php and ends with ?>.
• You can also use <? ?> if short tags are enabled on your php server.
• All valid statements end with ";" a semicolon.

The syntax of php should therefore is something like


<?php

PHP Codes;

?>

<!--First PHP Program-->


First PHP Program

Here it is assumed that you have installed the apache server for parsing PHP scripts
on your machine. If you do not have any PHP parser installed on your machine. Then
it is advised to do so before proceeding.

Once your web server is up and running, enter the following lines of codes in any text
editor and save it as firstpage.php. Notice the extension .php. This extension is a must.
On windows it is advised, while using notepad as editor, to save the file keeping the
file type as all types. Alternatively you can give the file name in quotes also.

<html>
<head>
<title>First PHP page</title>
</head>
<body>
<?php
echo “Hello World!”;
?>
</body></html>

Now copy the file in the root directory of your server. To view this page you should
type the address of the directory and the file name. If you have saved the document on
your local machine then
http://localhost/firstpage.php should work.

Here note that, If you have multiple servers installed on your machine then it might
not work. You will have to explicitly specify the port number also, in this case. The
page can be found by entering the address as below
http://localhost:8080/firstpage.php - Where 8080 is the port number where the server
listens to incoming connections.

Now notice the structure of the PHP script. Most of the time while writing a web
application the PHP script is embedded in the HTML code. The “echo” is the PHP
function which writes the output to response of the server.

Here the Apache server (Or any other PHP parsing server) will write the code up to
<body> segment to the response. When it encounters the <?php code it parses the
coming statements as PHP. It echoes or writes the text “Hello World!” to the
response. Finally it sends the remaining html code.

So do remember this PHP function echo which will be the most widely used function
in your PHP code.

Server Side Include (SSI) in PHP


Server Side Includes In PHP
<!--Write Here-->

Many a times we put the reusable codes in a separate PHP file. We, then include this
file in any other file
where required. This provides an excellent way to maintain a system. When we
include a file, we can assume
that the source code of that file copied at place of inclusion as it is while runtime.

The syntax to include a file is as below

<?php include ‘includefile.php’; ?>

We often use the relative path of the file to be included.


Here while including the files, it should be kept in mind that no file can include itself.
That is the file
inclusion should not be recursive. That will result in a fatal error and the program will
be terminated by the
PHP parser. A typical illustration of such include is explained below.

Let’s suppose that we have two files A and B. If file A includes file B and file B
also includes file A,
then that will be a recursive include.

When should we use PHP includes

Some practical examples/ scenario where PHP includes are commonly used are as
below.

• Writing the footer in a separate file footer.php and including this file in every
other file. This
way we ensure that the footer is displayed on all the web pages. Also if we
want to modify the footer any
day, then we will have to modify only the footer.php
• Declaring all the static messages in a separate file “message.php” and
including this file in
whichever file we need to display message.
• Declaring all the userids and passwords to required for connecting to your
mysql database in a
separate fie “secret.php”. We can then include this file in every file where we
need to connect to the
database. This way we can change the passwords frequently and update the
file “secret.php “. Also if you
export your source code to somewhere else, you will be required to modify
this secret.php only!

PHP Variables
Variables in PHP
In PHP, variables need not be declared separately before using them. You can
introduce a new variable anytime you wish to use them. However it is recommended
to declare your variables in chunk before using them, to avoid similar variable names
while introducing new variables.

The data type of a variable introduced at anytime is same as the data type of the value
being passed to it for the first time. So if a value of 5 is moved to a variable while
declaring it, the variable will become integer.
The variable of data type String is created when some string value is passed to it. The
simplest way to create a string variable is like this, $string = ""; Once introduced, this
variable can be used at any subsequent PHP statement.

Variable names in PHP are case sensitive. So $category and $Category are different.
Once a variable is declared it can used any where within the program. The following
rules should be kept in mind while defining a new variable name

• All variables in PHP start with $ sign.


• A variable name must start with a letter or an underscore "_".
• White space is not allowed in the name of a PHP variable. Instead one should
use either underscore or Capitalize the first letter of second word to make the
name readable when using multiple words while defining the PHP variable.
Though you can use all small or all capital letters also.
• I have never had to think about the maximum length of the name of a PHP
variable. So I do not know this thing this time. :)
• Only alphanumeric characters and underscore are allowed in PHP variable’s
name.

Some valid variable Names in PHP


$categroy
$Category
$categorymaster
$categoryMaster
$category_master
$category_1

Some invalid variable Names in PHP


Category (Variable name does not begin with $)
$Category! (Only alpha numeric characters and _ allowed)
$category master (There should not be any space in between the two words)

Operators in PHP
PHP Operators

All the valid operators are available in PHP just like any other language. A list of
operators is given below.

Operator Description Example


+ Addition if x=1, x+2 will be 3
- Sutraction if x=2, x-2 will be 0
* Multiplication if x=2, x*2 will be 2
/ Division if x=2, x/2 will be 1
++ Increment if x=1 x++ will be 2
-- Decrement if x=2, x-- will be 1
Operator Description Example
if x=2, x+=3 will set the value of 5 in x. Similary
+= Set RHS + LHS to LHS
other operatos like -=, *=, /= and .= etc.
Logical Operators in PHP

Logical operators when evaluated, return a boolean value.i.e true or false. For
Example, if x=2 and y=3 then the expression x>y will evaluate to be false. These
operators are mostly used in looping and conditional processing. We will very soon
learn these topics.

Operator Description Example


> Greater than if x=1, x>2 will return false (0)
< Less than if x=1, x<2 will return true (1)
>= Greater than or Equal to if x=1, x>=1 will return true (1)
<= Less than or Equal to if x=1, x<=2 will return true (1)
!= Not Equal to if x=1, x!=2 will return true (1)

The following example will clarify these concepts.

Example

The PHP Code Output of this code


<?php
$x = 2;
$y = 3; $x>$y =
echo "$x > $y = ".($x>$y)."<br>"; $x<$y = 1
echo "$x<$y\ = ".($x<$y)."<br>"; $x!=$y = 1
echo "$x!=$y = ".($x!=$y)."<br>";
$x>=$y =
echo "$x>=$y = "($x>=$y)."<br>";
?>

Notice the output of this code. The print function echo does not print null or false
values. However it prints the "true" value as 1.

Boolean Operators in PHP


Boolean operators are used to join two logical expressions. The resulting joined
expression returns true or false depending on the values of the individually joined
expressions and the boolean operator. This will be clarified with an example.

Operator Description More Description


Expression joined by this operator return true only if the
&& AND individual expression evaluate to true. In all other conditions,
it returns false.
Expression joined by OR operator returns false only if all the
|| OR individual expressions also evaluate to false. In all other
conditions, it returns true.
Negates an expression. True becomes false and false becomes
! NOT
true.

Switch statements in PHP


Conditional Calculations in PHP

Many a times, we want to do something in a specific condition and entirely different


thing in some other condition. To handle such type of conditional processing, PHP
supports the following condition handling statements.

• The if...else Statements


• The if...elseif Statements
• The Switch Statements

We will learn about these one by one.

if...else Statements in PHP

The simplest form of a PHP if else statement is as below.

if (a==b)
Do this;
else
Do this;

Note that the statements immediately following the if or else statement are executed.
If you want to execute a chunk of codes conditionally then you should include the
code inside braces as given in the example below.
if (a==b) <-- Condition inside the braces
{
PHP Statement 1;
PHP Statement 2;
}
else
{
PHP Statement 3;
PHP Statement 4;
}

What if more than one statements are there? In that scenario you should use the else if
statements as explained below.

if...elseif...Statements in PHP

The PHP syntax of an if..else if... statements are very much similar to the if...else
statements. Only change here is that you validate your condition before the beginning
of the else block also. The syntax is as given below.
If(a==b) <-- First condition
{
PHP Statement;
}
elseif(b==c) <-- Second condition
{
PHP Statement;
}
else <-- This block executed if above conditions fail.
{
PHP Statement;
}

Switch Statements in PHP

If you do not like nesting and you can do away with complex conditions resulting into
true or false, PHP switch is for you. The syntax of the PHP switch is as given below.

switch($var) <-- $var is the condition here


case $var=1: <-- The PHP statements are executed if $var is 1.
{
PHP Statements;
}
case $var=2: <-- The PHP statements of this case
are executed if $var is 2.
{
PHP Statements;
}

• We use switch statements to make the code maintainable and easy to


understand.
• A switch statement begins with the keyword switch followed by the variable
name in braces. After this different cases follow. These cases are chunks of
codes which are executed when the value of the switch-variable($var) equals
the case value(1 or 2).
• The valid case and all subsequent cases are executed. In this sense the switch
is different than traditional if else statement in PHP.
• To avoid the subsequent cases to be executed. One should use the break
statement. at the end of a case.
Arrays in PHP
Arrays in PHP

Let us suppose that we need 10 variables of similar data types to store ten web
addresses. We can use ten variables to store the information. Managing 10 variables
will be difficult. PHP provides Array to store similar values. Many a times arrays are
used to get a ramdom number out of fixed set of numbers. The syntax to declare an
array in PHP is as given below.

$arr = array("1","2","3");

Alternatively we can create a new similar array with same values as below.
$arr[0] = "1";
$arr[1] = "2";
$arr[2] = "3";

To access any of the array element, we refer its position. The position begins with 0
(zero). For example the following code will output 3. You may or may not create an
empty array in php. In the example above, first array element is created on the first
statement then other elements are appended to the array.
echo $arr[2];

Apart from the above type of arrays where we refer an array element by its position,
PHP has another type of array, the associative array. We will learn about associative
arrays in the next section.

Associative Arrays in PHP

Unlike the numeric type of arrays discussed in the previous section, the elements of
an associative array is accessed using a key name also. This key name is assigned to a
position while creating the array. The example of creating an associative array is as
given below.

$person = array(
"name"=>"John",
"age"=>"23",
"address"=>"36,Chinatown"
);

Now We can access each element of the above array by its key or by its position as
described below.
//By key
echo "Name is ".$person["name"]."<br>";
echo "Age is ".$person["age"]."<br>";
echo "Address is ". $person["address"]."<br>";
The output of the above code is given below.
Name is John
Age is 23
Address is 36,Chinatown

Unset An Array in PHP


We can unset any specific value of array, or the complete array itself. When we unset
an array in PHP the array or array element becomes empty or null. To unset an array
element we will use the following syntax.
unset($arr[0]);

To unset an associative array element we will use the following syntax.


unset($arr["first_element"]);

If we access an array element which we have unset, the null value is returned.

If we want to empty a whole array (all elements of the array are unset at a time), we
can use the following code.
unset($arr);

Looping in PHP
Looping in PHP
Many a times we want to do some specific calculations repeatedly. To do so PHP
provides the following looping statements.

• while
• do...While
• for
• foreach

We will learn about these iteration methods one by one.

PHP while Statements


The syntax of a while statements in PHP as given below.

while(condition)
{
do this;
}

• The PHP continues to "do this" till the "condition" remains false.
• The condition is evaluated at the beginning of each iteration.
• If the condition is false, at the beginning of any iteration (even the first one),
the PHP comes out of the loop.
The syntax of a while statement given above is the most commonly used syntax.
Alterantively if the chunk of PHP statements to be executed is large, you can use the
endwhile instead of the pair of braces. The syntax of doing so is as below.

while(condition)
do this;
and this;
endwhile

Example: The following code will print the the numbers from 1 to 10 one after the
other. Use this if only one statements has to be iterated over.
$i = 0;
while($i<10)
echo $i++."<br>";

Example: The following code will again print the numbers from 1 to 10 two in a line;
Use this (Or the next method) method if multiple statements are to be iterated over.

$i = 0;
while($i<10)
{
echo "Cureent number is";
echo $i++."<br>";
}

Example: The following code will give the same output as the above example. Notice
the usage of colon ":" and semicolon ";". Use this (Or the next method) method if
multiple multiple statements are to be iterated over.

$i = 0;
while($i<10):
echo "Cureent number is";
echo $i++."<br>";
endwhile;

The PHP do-while Statements


The syntax of a do-while statement is as given below.
do{
this;
}while(condition)

• Unlike the while statements, do while condition is checked at the end of each
iteration, guranteeing that the loop will be executed at least once. Use this loop
when you have any such requirement.
• do-while loop in PHP is executed until the condition becomes FALSE.
• You can use do while loops also in place of while statements (though not
recommended) by using proper break statements (A break statement in PHP
loop takes you out of the immediate loop irrespecitve of the looping
condition).
Example: The following code prints the values 1 to 10 one after another;
$i=0;
do{
echo $i++."<br>";
}while($i<=10)

Notice the difference from the similar loop using the while statement.

The for loop in PHP


The syntax of a PHP for loop is as given below.
for(statement1; condition; statement 2)
{
do this; //<- chunk of statement to be
// iterated over.
}

//statement1 <-Executed once only at the beginning of the loop


//condition <-Evaluated before starting each iteration (The first
// one also)
//statement 2 <-Executed at the end of each iteration.

The for loop is one of the most used loops in PHP. This loop is very much similar to
the for loop in C and Java.

Most of the statement 1 is the initialization of a counter variable, condition is the


condition which is to be evaluated and statement 2 is the increment or decrement
statement.

• None of the three expressions are mandatory, However you must use the
semicolon.
• Just like PHP while, PHP for also has its endfor. Syntax is similar to endwhile.

Example: This example outputs the numbers from 1 to 10. Use this if you have to
execute only one PHP statement.
for($i=1;$i<=10;$i++)
echo $i."<br>";

Example: This example again outputs the numbers from 1 to 10. Include your PHP
statements inside a pair of braces if you want to execute multiple PHP statements at a
time.

$i=0;
for(;$i<10;)
{
echo $i++."<br>";
}
Example: This example again outputs the numbers from 1 to 10. Notice the usage of
colon(:) and semicolon(;).

for($i=1;$i<=10;):
echo $i."<br>";
$i++;
endfor;

The foreach statements in PHP

The foreach statement is a special looping facility to iterate over array elements. The
syntax of a foreach statement is as given below.

foreach (array as value)


statement;

This will become more clear by examples. Example: Suppose that we have an array of
five integers. We want to multiply each of these elements by 4. We can do so by using
a while loop as below.

$array = array(1,2,3,4,5);
$i=0;
while(i<5){
$array($i) = $array($i) * 4;
}

We can do the same thing by using the foreach loop as below.

$array = array(1,2,3,4,5);
foreach($array as $value)
$value = $value * 4;

Notice that here $value acts as the array element at any iteration. Not the value only.
Because the changes to this $value are being stored as the changes in the array
elements.

Due to this we need to unset the reference to the last array element after the loop if we
do not wish to let the reference remain. We do so by using the unset() function. This
function breaks the refernce of the variable $value with the array $array element. Note
that if you come out of the loop using some break statement, then also the $value will
have the reference to the last accessed array element. unset($value) destroys all such
references.

We can also access each of the array elements of an associative array with their
respective key ids as below.

$array = array("name","age"=>"john","23");
foreach($array as $key => $value)
{
echo $key;
echo $value;
}

Functions in PHP
PHP Functions: ( )

Just like any other language PHP also, provides the function facility.

What are functions?

To do repetitive, complex or out of sequence one time calculation, we create a


function. whenever we need to do the certain calculation we just make a call to the
function.

Functions are widely used concepts present in almost every scripting language. They
make the code look simpler and easy to maintain.

The PHP functions are basically of two types.

• User Defined functions


• Inbuilt functions

Lets us now learn about these functions one by one.

User defined functions

The PHP functions can take parameters and return values also. We will learn about
them with examples. The syntax of a function is as given below.

function function_name($parameter1, $parameter2){


PHP Statements;
return $return_value;
}

The following example will make the things clearer.

echo get_mean(1,2,3);

function get_mean($x,$y,$z){
return ($x+$y+$z)/3;
}

The above example will output the value 2.


Note that the scope of the variables defined a function is limited to the function itself
unless you
declare them as global variables. So, If you write and use a function like this

$a=1;
$b=2;
$c=3;
$mean = get_mean($a,$b,$c);
echo $mean;

function get_mean($x,$y,$z){
($x+$y+$z)/3;
}

and expect the output to be 2, It will not happen. You will have to write a return
statement inside the function to retrieve the value of the expression outside the
function!

PHP Inbuilt functions

PHP provides several inbuilt functions for common calculations. You have to do
nothing to use these functions. If the corresponding module is loaded in your web
server, you can just use these functions like you wrote them yourselves.

Some common PHP functions are time(), date(), rand();trim(); str_replace() etc.
We will learn more about the common functions in the PHP functions section.

GET Array in PHP


The $_GET Array in PHP

Before learning this array you might want to learn the HTTP GET and POST methods
in the HTML section of this website.

The forms or any parameter passed to a PHP page with GET method can be retrieved
in the PHP page using the inbuilt array $_GET[]. You can retrieve the array values
using by using the names of the parameters.Hence $_GET Arrays are associative in
nature.

The following is the syntax of a get array.


$user = $_GET["userid"];

An example has been given in the next section which displays a webform with two
fields. The form is submitted to the same page. The script displays the parameters
submitted using the GET method. A form is submitted using the GET method when
the "method" attribute of the form is set to GET or this attribute has not been set at all.

Example of Form processing using the $_GET[ ] Array


Save this file as get_array.php.
<html>
<head>
<title>$_GET Array</title>
</head>
<body>
<?php
echo "<br>User Id is:".$_GET["user"];
echo "<br>Password is:".$_GET["password"];
?>
<form action=get_array.php method=GET>
UserId:
<input type=text name=user><br>
Password:
<input type=text name=password><br>
<input type=submit value=Submit>
</form>
</body>
</html>

POST Array in PHP


The $_POST Array in PHP
<!--Write Here-->

Before learning this array you might want to learn the HTTP GET and POST methods
in the HTML section of this website.

The form fields or any parameter passed to a PHP page with POST method can be
retrieved in the PHP page using the inbuilt array $_POST[]. You can retrieve the
array values using by using the names of the parameters.Hence $_POST Arrays are
also associative in nature.

The following is the syntax of a get array.

$user = $_POST["userid"];

An example has been given in the next section which displays a webform with two
fields. The form is submitted to the same page. The script displays the parameters
submitted using the POST method. A form is submitted using the POST method when
the "method" attribute of the form is set to POST or this attribute has not been set at
all.

<!--Comment of this block-->

Example of Form processing using the $_POST[ ] Array


<!--Write Here-->
Save this file as post_array.php.
<html>
<head>
<title>$_POST Array</title>
</head>
<body>
<?php
echo "User Id is:".$_POST["user"];
echo "<br>Password is:".$_POST["password"];
?>
<form action=post_array.php method=POST>
UserId:
<input type=text name=user>
Password:
<input type=text name=password>
<input type=submit value=Submit>
</form>
</body>
</html>

Request Array in PHP


The $_REQUEST Array in PHP

Before learning this array you might want to learn the HTTP GET and POST methods
in the HTML section of this website.

The form fields or any parameter passed to a PHP page with POST method can be
retrieved in the PHP page using the inbuilt array $_REQUEST[]. You can retrieve the
array values using the indices (Positional values of parameters) or by using the names
of the parameters. Using the names to retrieve the values is recommended.

The following is the syntax of a get array.

$user = $_REQUEST["userid"];

An example has been given in the next section which displays a webform with two
webforms. The first one submitted using the GET method while second one, using the
POST method. The form is submitted to the same page. The script displays the
parameters submitted using the POST method as a response. A form is submitted
using the POST method when the "method" attribute of the form is set to POST.

Example of Form processing using the $_REQUEST[ ] Array

Save this file as request_array.php. If you do not understand the cookie, leave it. You
will read about the PHP cookies in the coming sections. Here the point is related to
the request method. That the request array can be used to access the cookies also.
<?
if(!isset($_COOKIE["request_cookie"]))
setcookie("request_cookie","tutorialindia.com");?>
<html>
<head>
<title>$_REQUEST Array</title>
</head>
<body>
<?php
echo "The cookie is: ".
$_REQUEST["request_cookie"];
echo "<br>User Id is: ".$_REQUEST["user"];
echo "<br>Password is: ".$_REQUEST["password"];

?>
<form action=request_array.php method=GET>
Using the GET Method: UserId:
<input type=text name=user>
Password:
<input type=text name=password>
<input type=submit value=Submit>
</form>
<form action=request_array.php method=POST>
Using the GET Method: UserId:
<input type=text name=user>
Password:
<input type=text name=password>
<input type=submit value=Submit>
</form>
</body>
</html>

Date Handling in PHP


PHP Date: date()

This is an important section as you will certainly need the date() function sooner or
later. The date function returns a UNIX timestamp in the format mentioned by you.
The syntax of this function is very easy. It's as mentioned below.
date(desired_format, UNIX_timestamp)
desired_format -> The format in which the time
stamp is to be converted into.
UNIX_timestamp -> This is the time elapsed in
seconds since 01-01-1970 00:00:00.

If no timestamp has been specified, the date function returns the current date in the
desired format. If the format has also not been specified, a warning is issued.

The following example will make it clear.


<?php
echo date("Y-m-d",60*60*24)." ";

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

?>

The output of the above code is as given below.


1970-01-02 2008-07-01

We will now learn more about different important formats (Actually formatting
options) in the next section.

Calculate future and past dates in PHP


Let us learn how to get dates in future and in the past.
The date in future or in the past can be retrieved by the passing the exact number of
seconds since 1st Jan 1970. To do so, first we need to know the current timestamp. In
PHP we have inbuilt function time(). Function time(), returns the current UNIX
timestamp. Ok so it solves one of our problems. All that's needed now is to add or
subtract necessary number of seconds from this timestamp to get a future or past
timestamp. How to get the future or past timestamp, is no more a secret now. The
following examples show you to retrieve the current or past date in PHP.

1. Dates in Future

For this we retrieve the current timestamp using the PHP function time() and add the
number of seconds left to get the future date into it. So, the date next week on today's
day will be
date("Y-m-d",time()+60*60*24*7);

The output of the above script is 2008-07-08

Similarly the next year:

date("Y-m-d",time()+60*60*24*365);

The output of the above script is 2009-07-01

2. Dates in the Past

For this we retrieve the current timestamp using the PHP function time() and subtract
the number of seconds passed since the date in the past. So, the date in the previous
week on today's day will be

date("Y-m-d",time()-60*60*24*7);

The output of the above script is 2008-06-25


Similarly the date exactly one year in the past:
date("Y-m-d",time()-60*60*24*365);

The output of the above script is 2008-07-01

Now, That is not all what PHP date can do. The power of this function lies in
returning you the date in whichever format you want. The next section illustrates
some important formats.

Date formats in PHP

A few of the important date formats has been mentioned here. These date formats
should satisfy almost all your basic needs. However, You can visit
http://www.php.net to learn all about different date formats and which suits you the
most.

Format Description Example based on current time.


d Returns the current day 01
D Returns the name of the day Tue
F Full month name July
m Month number 07
Y A four digit year 2008
y A two digit year 08
H Hour in 24 hr format 19
m minutes 07
s seconds 47
c Complete date c

You can use optional separator in between to get your time in desired legible format.
The two examples below display the current date. One without separator and other
with separator.

<?php
echo "Current time is - ". date("dmYHms");

echo "<br>Current time is -". date("d-m-Y H:m:s");


?>

The output of the above script is as below.

Current time is - 01072008190747


Current time is -01-07-2008 19:07:47

Note:- The date on which the expressions on this page were evaluated was 01st July
2008.
Session handling in PHP using Cookies
Cookies in PHP
What is a cookie?

Cookies are piece of information stored on user machine. This information is sent by
the browser every time the browser connects to the web server. A typical cookie
might contain the user name of a logged user, preferences of a user, previous visists of
a user etc.Cookies help the web designers to keep track of specific user.

The scope of this tutorial about cookies is as described below.

• How to set cookie in PHP.


• How to retrieve cookie in PHP
• How to delete or destroy a PHP cookie.
• When should we use cookie.

Set a cookie: setcookie()


To set a cookie in PHP, the inbuilt function setcookie() is used. This function defines
the PHP cookie. This cookie is then sent as HTTP request header. The syntax of this
PHP function is as given below.
setcookie("cookie_name","cookie_value","expiry_time");

The PHP Cookie also some other arguments alos. You can learn them at the official
website of PHP.

Each of the above three argurments (parameters) are discussed below.

1. cookie_name - This is the name of the cookie to set. This is a mandatory


parameter. You will refer the cookie with this name only.
2. cookie_value - This is the value of the cookie. It is optional. If this value is not
specified, a null value is set. To access this value you need the cookie name.
3. expiry_time - This is an optional parameter. If this parameter is not specified,
the cookie is valid only for the current browser session. At the end of the
browser session, the cookie will be cleared. This value is given in the form
Unix timestamp. So you should use the PHP inbuilt function time() to set this
value. Also, this value is relative to client machine not the server.

Since the PHP cookie is sent as the HTTP header, It must be set before any output is
sent.

Last but not least, PHP Cookies are sent by the server but they are created on the
client machine by the browser only not the server.However, we often use the terms
like "cookie set by server etc."

1. setcookie("user","john");
2. setcookie("user","john",time()+60*10);
The first PHP cookie example sets the cookie named user. This cookie will be deleted
by the browser as soon as the current browsing session ends. That is the browser
window is closed.

The first PHP cookie example sets the cookie named user. This cookie will be deleted
by the browser as soon as the current browsing session ends. That is the browser
window is closed.

The example 2 of setting cookie in PHP set the similar cookie, but this time this
cookie will be persistent for 10 mins. Even if the user closes his browser, The browser
will not delete the cookie this time, rather it will wait for exactly 10 minutes before
clearing the cookie.

P.S. - You can see the usage of unset function in the arrays section.

Access a PHP cookie: $_COOKIE[ ]

The $_COOKIE[ ] Array

PHP provides inbuilt array $_COOKIE[] to access the cookies. These cookies are
accessed by using their key names. The key names are specified as the name
parameter of a setcookie() function. So, to retrieve a PHP cookie you simply have to
use this array with appropriated key value. The example below retrieves the cookie set
in the previous example.

$username = $_COOKIE["name"];

The $username will contain the value "john" after this statement is run.

The $_REQUEST[ ] Array

This array also, has access to the cookie set by the browser. The previous statement
can be modified to access a cookie by using the $_REQUEST[] array as below.

$username = $_REQUEST["name"];

The $username will contain the value "john" after this statement is run.
The $_REQUEST[] array is also used to retrieve form data also. We will learn about
the PHP $_REQUEST[] array in the coming pages. For now lets learn how to destroy
a cookie

Destroy a PHP Cookie: unset()


There is no separate function to destroy or unset a PHP cookie. Shocked? I also felt
the same when I learnt this for the very first time. As we know that the cookies are
created by browsers. Hence the onus to destroy a cookie also lies with the same
browser. You only instruct the browser to delete the cookie by setting the time in the
past. You do so by using the same old setcookie() function. The example below tells
the browser to clear the cookie.
setcookie("name","",time()-60);

Notice that the cookie_name is the same as the name of cookie we want to clear.

When should you use PHP cookie

As the cookies are placed on client side, cookies should be avoided when involving
monetry transactions. Other sensitive information should also not be stored as
cookies.

However you can use cookies for normal login systems etc. Cookies are supported
over SSL connections also, so there is no problem even if you plan to use cookies. In
fact one of other parameters of PHP cookie is specific to this purpose only.

That all for now about cookie. May be I will write a separate article or add a separate
page about the Advanced concepts in PHP cookies sometime in future. The tutorial
itself has crossed the limit, so We will directly do a project all about cookies in the
project section of this PHP tutorial instead of doing examples.

Session Handling in PHP using


$_SESSION
Session Hanlding In PHP: setsession();

What is a PHP session?

You can assume the session in PHP or in other scripting language for that matter, as
something which keeps track of a specific request. The normal without any session
request is processed by a web server as below.

• The browser makes a request.


• The web server accepts the request and processes it. Finally it sends back
some response to the requester (the browser, mostly) and forgets about the
request.
• If the same browser again makes some other requests, the web server does not
know that it has just served this specific browser. It treats the request as a new
request.

A typical transaction using the session object will be something like this.

• The browser makes a request to the web server.


• This time the web server creates a web session or simply session object on its
own machine(web server's) and assign some unique name or id to it. This
unique Id is often called as the session id.
• The web server processes the request and sends the session id as header while
sending response back to the browser.
• When the browser makes request to the web server, it sends the session id also
with the request. The web server check for availability of the session
corresponding to the id. If it finds the session live, It knows that this is not the
first time the browser has requestd some services!

Why do we use sessions?

We use sessions to generally keep the track of a successfully logged in user. We store
some user-specific information in the session object. This information might be the
user id of a successfully logged in user, or the shopping contents on a cart based
website etc.

Advantage of using SESSION object.

As compared to cookies, the advantage of using a session is that all the information
are stored on the server machine only hence it is more secure.

Disadvatnage of using session.

The performance might degrade if lots of session objects co-exist on the server
machine. This will result in delayed response and might annoy the end users.
However using good dedicated hosting solutions may help you. With dedicted hosting
the server resources are not shared by anyone else. All the CPU time is available to
your own application only, Which results in better performance.

After so much gyan let us learn PHP specific Sessions. In the next section we will
learn how to create a PHP session.

Create PHP Session Object: session_start();

You need to start a session in PHP before you can add information to this object. The
function session_start() creates a new session object. This function does not take any
argument. If a session is already active, this function is ignored.

To save a value to your just started session variable, you should use the inbuilt PHP
array $_SESSION[ ]; This array is again used to retrieve values also. The following
script starts a new session if one not already active and saves the user name as "john".

session_start();
$_SESSION["user_name"] = "john";

To retrieve the value of user name, just use the $_SESSION["user_name"]. Simple!
Isn't it?

Destroy A Session: session_destroy()


Unset a session value
To unset a session value, use the same old unset() function. The following code
destroys the variable. After unsetting this variable the isset() function returns false for
the variable.
unset($_SESSION["user_name"]);

Destroy a session completely

If you want to destroy a session itself. You can destroy a session completely in PHP
using the session_destroy() function. The example below destroys the session
completely.
session_destroy();

Working example on PHP Sessions


The script below creates a new session. It then shows the no of views till the no. of
views reaches 5. Once the page has been viewed for 3 time, the script destroys the
session and starts a new session.
<?php
session_start();
if(isset($_SESSION["user_visit"]))
{$_SESSION["user_visit"] = $_SESSION["user_visit"] + 1;}
else
{
$_SESSION["user_visit"]=1;
}
if($_SESSION["user_visit"]==5)
session_destroy();
?>
<html>
<head>
<title>Session Visits</title>
</head>
<body>
This is your <?php echo $_SESSION["user_visit"]?> visit!
</body>

</html>

More example on PHP Sessions


OK, now The example below is a little more elaborate and it shows how a typical
session handling can be done. If you learn this, you will be able to create a typical
login application easily.

<?php session_start();
if(isset($_SESSION["user_name"]))
if($_GET["destroy"]=="yes")
{
unset($_SESSION["user_name"]);
session_destroy();
}
if(!isset($_SESSION["user_name"]) &&
$_GET["user"]!="")
$_SESSION["user_name"] = $_GET["user"];

?>
<html>
<head>
<title>Session Example</title>
</head>
<body>
Welcome <?php echo $_SESSION["user_name"]; ?>
<form action="#">
Input your name here: <input type=text name=user>
<input type=submit value=Submit>
</form>

<form action="#">
<input type=hidden value=yes name=destroy>
<input type=submit value="Destroy Previous Session">
</form>

<p>
The first time you input your name,
It will be stored as a session object.
So every time you pression submit button
or refresh the page, you will se the name
you entered for the first time!.
</p>
</body>

</html>

Notice that the session has been started before any HTML output has been sent.
Just like setting a cookie, a session must always be started before committing any
output.

You might also like