PHP Tutorial
PHP Tutorial
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.
PHP Codes;
?>
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.
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.
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.
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
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.
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.
Example
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.
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;
}
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.
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.
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
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
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;
• 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 is one of the most used loops in PHP. This loop is very much similar to
the for loop in C and Java.
• 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 statement is a special looping facility to iterate over array elements. The
syntax of a foreach statement is as given below.
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;
}
$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.
Functions are widely used concepts present in almost every scripting language. They
make the code look simpler and easy to maintain.
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.
echo get_mean(1,2,3);
function get_mean($x,$y,$z){
return ($x+$y+$z)/3;
}
$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 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.
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.
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.
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.
$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.
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.
$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.
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>
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.
?>
We will now learn more about different important formats (Actually formatting
options) in the next section.
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);
date("Y-m-d",time()+60*60*24*365);
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);
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.
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.
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");
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 PHP Cookie also some other arguments alos. You can learn them at the official
website of PHP.
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.
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.
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
Notice that the cookie_name is the same as the name of cookie we want to clear.
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.
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.
A typical transaction using the session object will be something like this.
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.
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.
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.
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?
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();
</html>
<?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.