You are on page 1of 134

PHP

Install PHP 5 Apache MySQL on Windows


using WampServer
Installation of WAMP (Apache, PHP and MySQL for Windows).
WAMP Installation
WAMP (Apache, PHP and MySQL for Windows) provides the popular combination of Apache
with the PHP server-side language and the MySQL database in one easy-to-install package.

1. download latest release of wampserver 2 from http://www.wampserver.com/en/.


2. Before install WAMP server , check wethere you have already installed. If yes, first uninstall
the existing installation of apache.
3. Once download double-click the file to launch the installer.
4. The setup is self-explanatory. At one point you will be asked where you want to have your
www root folder. This www folder is simply where your web pages will be loaded from. It
doesn't really matter what you choose and you can always change it later.

After the installation you should have a fully functional Apache web server with PHP and
MySQL.

5. To launch your web server go to Start › All Programs › WampServer (or wherever you
installed WAMP to) and click start WampServer.

You'll notice a small icon in the bottom right corner of your screen changing from red to white.
That was just the WAMP server that booted up. By left-clicking on the icon you'll get to the
server options. The meaning of the icon status changes are shown below:

Offline mode means that only you, from your computer, can access your server. External access
will be blocked (indicated by the black lock in the icon). This is the default setting and should
always be used for website testing.

Online mode on the other hand means that everyone can access your server from anywhere. This
is option is for using your computer as a live web server should you intend to do that.

Now we're going to try to access your server locally with a web browser:
1. Make sure WAMP is up and running in offline mode.
2. Enter localhost into your browser bar and hit enter.

If you didn't provide a different www root directory when installing WAMP the default page
should have loaded:
What localhost does is simply to look for an index file (in this case index.php) in your www root
folder and load it into the web browser. You can go to that folder (usually C:/Program
Files/wamp/www/) and check for yourself that such file indeed exists.

You could now start building your own website by replacing the index file with your own index
file (index.php, index.html, ...). Every time you'd made a change to your website you'd hit F5 in
your web browser to load the most recent version.

Accessing your server from anywhere

Suppose you've created a cool website and want to show it to your friend who's living halfway
around the globe, sitting in front of his computer. You only have your website on your local
machine. Very similar to the looking up a web page with its IP exercise you're going to tell your
buddy to enter your IP into his web browser bar.

Your friend's web browser will then try to establish a connection with your computer over port
80 (standard port for speaking to web servers). Apache will catch this request and send the index
page located in your www root folder to the web browser which in turn will interpret its
containing HTML code and display it as a good old web page.

However, if WAMP runs in offline mode your friend will see the following in his web browser
upon entering your IP:
WAMP external access error
Try it for yourself:
1. Make sure WAMP is running in offline mode.
2. Enter your IP 78.8.6.29 into your web browser bar and hit enter.

To allow external connections to your server you have to restart WAMP in online mode.
1. Left-click the WAMP icon and select Put Online.
2. Wait for the icon status to change to white again.
3. Enter your IP 78.8.6.29 into your web browser bar and hit enter.
4. If you get the same forbidden page as before hit F5 to let the browser load the newest
version.
5. If it's still not working you probably have to enable port 80 forwarding in your router
configuration.
Finally your buddy can see your homepage!

WAMP external access success


Change Apache's www root directory

Sometimes it's necessary to change your current www root folder to something else. Maybe you
have all your work files on a different partition than where you installed WAMP to or you have
several websites you're working on and need to make one of them your primary site for a while
(the one that shows up when entering localhost).

Anything that has to do with Apache configuration can be done within a file called httpd.conf.

1. WAMP provides quick access to certain important files, one of them being httpd.conf.
2. Left-click WAMP icon and select Config files › httpd.conf.
3. The file will probably open up in Notepad.
1. Press Ctrl+F and enter documentroot.
2. Make sure case sensitive search is disabled and hit enter.
3. You'll find some descriptive text and below a line that looks like DocumentRoot
"C:/Program Files/wamp/www".
4. Copy that line then put a # in front of it: #DocumentRoot "C:/Program Files/wamp/www".
5. Paste the copied line just below and adjust it to where your custom root folder is located
(e.g. DocumentRoot "C:/my_cool_site").
6. Resume the search (usually by pressing F3) and you'll find a line like: <Directory
"C:/Program Files/wamp/www">.
7. Again copy the line, put a # in front, paste copied line below and adjust it (e.g. <Directory
"C:/my_cool_site">).
8. Save and close the file.

Whenever you make a change to httpd.conf you have to restart Apache for it to take effect. The #
we've added in front of the old lines turns them into a comment which Apache ignores. We just
added them so that we can easily switch back to an old configuration by uncommenting the lines.

1. Left-click the WAMP icon and select Apache › Restart Service.


2. Wait for the icon status to change to white again.
The root directory should now have changed to then one you've entered in httpd.conf. You can
test this by entering localhost in your web browser. The index page in that folder (or the lack
thereof) should show up now.

If you are done with the above sections, please get the assignment using below option.
Introduction
This chapter introduces about PHP, and its syntax and comments and echo statement and also
how to start writing program in PHP.

Syntax and Comments

Syntax

Always php syntax starts with <?php and ends with ?>. All scripts can be executed within this
block. There is one option in php.ini file that you can allow shorthand of using with <? and ?>.
But it is always good to use the standard way.

<?php

//your php code goes here;

?>

OR

<?

//your php code goes here;

?>

As shown above, your php code goes in between <?php and ?>. Each line of php code should
end with semi colon. Semicolon separates from one set of instructions with other.

well, why do we need to start and end php with a special syntax. Reason is that most of the time,
php code is written in between html code. So in one file, php script may start and end a few times
and rest of the code be html. This special syntax to start php code helps to mix the code with
html code as follows in the example.

<HTML>
<HEAD>
<?php
$username = "Elephant";
?>
</HEAD>
<BODY>
<?php
print("$username<BR>");
?>
</BODY>
</HTML>

As you see in the above example, both html and PHP is mixed in the code. So whenever <?php
syntax found, PHP interpreter started interpreting the code from there till it finds ?>.

Generally html code will be mixed with php code in normal programs except when we separate
the html content using smarty, which we will talk about the later part.

All php program files will be saved with .php extension. If it is used with other extensions it will
not work.

White spaces are ignored between php statements. That means, if you give say 50 or 60 empty
spaces after one php statement and to next statement, result will not be different.
Same with tab also. How many times you press tab it is not affecting the results.
Two statements, “echo” and “print” are used in php to output text. You can see it in example
programs below.

<?php
echo “Something is better than nothing”;
?>

<?php

echo “Something is better than nothing”;

?>
Output

Something is better than nothing

As you can see, both programs will output the same result, since PHP omits white spaces and
tabs.

Comments

We use // for one line comment or /* and */ for multiple line comments in a php program.

<?php
// this line is commented
echo “Today is Tuesday”;
?>

<?php
/* These are
multiple line
comments
*/
echo “Today is Tuesday”;

?>

First Program

<?php
echo “Welcome to siliconindia”;
?>

Output

Welcome to siliconindia

The above program is very simple one which display one statement. You have to save this as
.php extension in your document root directory and run it. If you look at the program , php
programs always start with “<?php” and ends with “?>” statements.

Examples:

How to display current date?

<?php echo “Today’s date is:”. Date(‘d-m-Y’);


?>

Output
Today's date is:17-03-2009

As you can see . operator (dot operater) is used to concatenate the string with function, date.

echo statement

The php echo statement is used to output the text to the browser. To output a text or string
you can use either string variable or use single quote or double quote directly.

Program

<?php
$name = “Tajmahal”;
echo $name;
?>

Output

Tajmahal

If you look at the above program we output a text called “Tajmahal”, but we did through
assigning it through a variable called $name. We will talk about the variable a little while from
now. Other way to output the same text is using either single quotes or double quotes as shown
in following example.

Program
<?php
echo “Tajmahal”;
//echo ‘Tajmahal’;
?>

Output

Tajmahal

As shown in the above program use either single quotes or double quotes to output a text to the
browser.

When you use echo statement you should not use quotes, if you want to use quotes, then you
have to escape quotes, otherwise error will be displayed. For example look at the following
program.

Program

<?php
echo “<font size=”5”>Tajmahal</font>”;
?>

Output

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'

So you can modify the program, so that this error will not come. Following program outputs
without error.

Program

<?php
echo “<font size=”5”>Tajmahal</font>”;
?>
Output

Tajmahal

So if you want to escape double quotes, within echo statement use ” . Or else you can use single
quotes instead of double quotes. Following is example how to use single quotes.

Program

<?php
echo “<font size=’5’>Tajmahal</font>”;
?>

Output

Tajmahal

Do it yourself

1) Write program to display your firstname in first line and second name in the second line.
2) Write program to display your name using tags <h1>,<h2>,<h3> and <h4> using echo
statement or print statement in each line.
3) Using date function, print out current date in the following format:
(Wednesday, May 27, 2009)
4) Can you write your name in arial font, of size 3 with red color and bold?
Data types
This chapter teaches about the data types available in PHP.

Data Types in PHP

Variables in php can store data of different types and different data types used for different
purposes. You can think of an example of adding two numbers say (100 + 101) and same way
you can’t do adding two characters say (C + D).

When you assign certain value to a variable, PHP will automatically try to guess the type of data
being stored and assign the data type to the variable, i.e PHP is a loosely typed language.

This is different from C or C++ where every variable has to be defined of a certain type, before
its use. In php, you can say n=2; that makes a variable n of value 2. But in C or C++, it will give
an error, you would first have to define n as integer before its use

You can store following different kind of data types in php variables:

Integer

Integer is a whole number without fractions. For example, -80, 345, 23456 etc are
integers. The range of integers varies according to the operating system, but we can use any
numbers from -2 billion to +2 billion.

Floating point numbers

This kind of data type used to store the decimal numbers including fractions. For
example 7.82, 3.14, 9.4567 are decimal or floating point numbers. This is also called real number
or float.

Character string

Character string is nothing but series of characters like NAME, CITY, welcome, etc.
Actually there is no limit of how many characters you can use.

Boolean
Boolean is a TRUE or FALSE value. It is actually two possible states TRUE or FALSE.
These are actually used for comparisons in conditional statements in php. For example, an
expression in php,($b < $c) can have result as either TRUE or FALSE.

Examples:

<?php

$number =10; //Here variable $number is an integer

$umber1 = 18.555 //Here variable $number1 is a float or double

$country = “INDIA”; //Here variable $country is a string

?>

As you can see in the above example, we don’t need to declare the datatype explicitly, like int,
float etc before the variable. While you create a variable with string, as shown in example, you
have to put the value inside a double quote or within the single qutote.

Following example shows how we can use BOOLEAN datatype.

<?php

$number1 = 15;
$number2 = 16;
if($number1<$number2)
{
echo "FALSE";
}

echo "<BR><BR>";
if($number2>$number1)
{
echo "TRUE";
}

?>
Output

FALSE

TRUE

As explained above a BOOLEAN datatype is used to validate a statement whether TRUE or


FALSE. If you look at the above example we declared two numbers and validating whether one
number is greater than other number and one is less than another one. Most of the time
BOOLEAN data type used with the conditional statements, which we will be covering in
upcoming chapters.

Type Casting

Type casting or type conversion refers to changing data type of one entity into another data
type. In PHP you can change data type of one variable into another data type. If you specifically
wish to override PHP's type conversion, you can perform what is called a type cast - you forcibly
convert a variable of type A to type B.

In PHP you can convert one data type into another in two ways. Using settype() function
or using (int), (bool), (double) keyword declaration.

First let us see how we can do type cast using settype() function.

<?php

settype($var1, “array”);
settype($var2, "bool");
settype($var3, "boolean");
settype($var4, "float");
settype($var4, "int");
settype($var5, "integer");

$var5 = '1';
settype($var5, 'integer'); //now $var5 converted into integer type
?>

If you look at above program we use settype() function for setting up a data type to one variable.
Another way, we can use keywords like int, float, boolean etc to change the data type as below.

<?php
$name = “1”;
$name1 = (int) $name; //converts $name1 to integer and stores into $name1
$name3= 98;
$name4= (boolean) $name3; //converts integer into boolean
$name5=66;
$name6 = (string) $name5; //converts integer into string

?>

The casts allowed are:


• (int), (integer) - cast to integer
• (bool), (boolean) - cast to boolean
• (float), (double), (real) - cast to float
• (string) - cast to string
• (array) - cast to array
• object) - cast to object
• (unset) - cast to NULL

Determining the datatype

To know what data type is used by a variable, PHP provides gettype() function. Like
settype() function to set the data type to a variable, gettype() used to output the data type used by
the variables.

<?php
$name1 = “INDIA”;
echo gettype($name1); //outputs string
$name2= 58;
echo “<BR><BR>”;
echo gettype($name2); //outputs integer
?>

Output
string

integer

Do it yourself

1) Write a program which converts one integer variable into a Boolean

2) You have one variable with $myvalue=”2”, how will you set the data type so that it will
become integer using settype() function?

Variables and Constants


This chapter teaches about variables and constants.

Variables and Constants

Variables

Generally variables are used to store the values. You can store values of different kinds like,
string, array, integer etc. In a single PHP file you can use a variable over and over a number of
times. Each time you use, you can assign a different values to the variable.

In PHP variables are defined as follows.

<?php

$variablename = value;

?>

As shown above, always PHP variables start with $ symbol and then variable name.

Examples:

<?php
$mycountry = “India”; //assigning a string to a variable

$number1 = 15; //assigning an integer

$number2 = 18.567; //assigning a float to a variable

echo $mycountry;
echo “<BR>”;
echo $number1;
echo “<BR>”;
echo $number2;

?>
Output
India
15
18.567

When you create a variable you should not forget the $ symbol. Let us see what happens when
we don’t create a variable name with $ symbol.

<?php
number1 = 100;
echo number1;
?>
Output
Parse error: syntax error, unexpected '='

So if you forget the $ symbol parse error will be shown.

PHP variable names are case-sensitive, which means $mycountry is different from $Mycountry.

To change a variable’s value just assign a new value to the variable. Just look at the following
example, how the variable’s value is changed.

Example:
<?php
$myname = “suresh” ;
echo $myname;
echo “<BR>”;
$myname = “ramesh”;
echo $myname;
echo “<BR>”;
$myname = "niraj";
echo $myname;
?>

Output
suresh
ramesh
niraj

If you look at the above example $myname variable name is changed twice and giving the output
differently each time since we changed the value for this variable.
Naming Conventions

When you create variables you should remember certain things so that variable name will
become invalid. So there are 3 rules, you have to remember before creating variables.

1) A variable name should always start with a letter or an underscore “_”


2) A variable can only contain alpha-numeric characters, i.e, (a-z, A-Z, 0-9 and _ )
3) A variable name should not contain any space. If you want to create a variable with more
than one word, you can use with capitalizing the next work without space or using underscore
“_” character.

Let us see by doing some examples, what error it gives when we create invalid variable names.

Example:

<?php

$my name = “something”; //invalid since space is there


echo $my name;

$my-name= “rahul”; //invalid since it contains other than underscore


echo $my-name;

?>

Output
Parse error: syntax error, unexpected T_STRING

So parse error will be shown when you create an invalid variable name.

Constants

Unlike variables, constants used to not to change the value. Once the value for a constant is
assigned then throughout the program the value cannot be changed for that. If you want to use
any configuration settings, you can use constants, so that the values will not change.

Following is how you can declare a constant in PHP.

define("CONSTANT_NAME", "value");
Example

<?php
define("COUNTRY", "India");
echo COUNTRY;
echo “<BR>”;
define(“NUMBER1”, 1000);
echo NUMBER1;
?>

Output
India
1000

If you notice above program, unlike variables, constants are defined in a different way. Constants
are declared using define function. Also one more important point to notice is that when you
output a constant, you should not use $ symbol, unlike PHP variables. If you use $ for a constant
before NUMBER1, then it will not output the constant’s value, rather it will give the output as
follows.

Notice: Undefined variable: NUMBER1

General way to use constant is by naming in capital letters, although you can use small letters
also.

As shown in the above example when you define a string constant, you have to declare it within
the quotes. If you are defining a integer constant you should not specify within the quotes.

Strings, Regular Expressions


A string is a series of characters. For e.g. “hello world” is a string. Being able to manipulate
strings is a valuable skill, especially in PHP. You'll most likely come across a programming
problem that requires you to find some data in a string.

String manipulation

Create and manipulate strings

Before you can use a string you have to create it! A string can be used directly in a function or it
can be stored in a variable. Below we create the exact same string twice: first storing it into a
variable and in the second case we send the string directly to echo.

Example:

$string = "Hello World!";


echo "Hello World!";
echo $string;

In the example above, first string will be stored into the variable $ string, while the second string
will be used in the echo and not be stored. Remember to save your strings into variables if you
plan on using them more than once! Below is the output from our example code. They look
identical just as we thought.

Output:

Hello World! Hello World!

String Concatenation

To concatenate two strings you will need the dot ( . ) operator, so in case you have a long string
and for the sake of readability you have to cut it into two you can do it just like the example
below.

Actually if you need to write a long string and you want to write it to multiple lines you don't
need concat the strings. You can do it just like the second example below where $string2 is split
into three lines.

Example 1:

<?php
$string1 = "Hello " .
"How are you?";

Example 2:
$string2 = "I,
am
Fine!";
echo $string1 . "<br>";
echo $string2;
?>

PHP Strings in Single and Double Quotes

As we saw in previous examples, strings are wrapped in double quotes. Using double quotes is
the primary method. Double quotes allow us to escape specials characters in our string. For
example, you can use single quotes with in double quotes.

Example - String in Double Quotes

<?php
$string = "It's a beautiful day today."
echo $string;
?>

Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.

Example - String in Single Quotes

<?php
$string = 'This is a string example in single quotes';
echo $string;
?>

Single Quotes vs. Double Quotes

Thou looking at single quote strings and double strings you may think there is any difference.
However, there are reasons for using single quotes and double quotes in a string.

Single quotes should be used when outputting HTML code. Since HTML tag attributes use
double quotes within themselves and since using double quotes in HTML tags is the convention,
therefore it is advisable to use single quotes when wrapping a HTML code in PHP. Here's an
example.

<?php
echo '<input type="text" name="first_name" id="first_name">';
?>

Double quotes are used when we want to use special characters in our strings such as new line
characters and . Single quotes will treat them as regular characters. Also when printing a variable
in a string, it is advisable to use double quotes.

Example:

<?php
$name = "Matt";
echo "Hello $name!";
?>

Output : Hello Matt

String Functions

Here we discuss few useful php functions, which you will be using frequently.

Strlen() function :

This function returns the number of characters in a string. It takes a string as an argument.

Example:

<?php
$str = "Hello!";
echo strlen($str);
?>

Output : The above example will output 6.

str_replace() Function :

This function replaces all occurrences of the search string in the main string with the replace
string. Let's look at the example below.

Example:

<?php
$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>
Output: The above code will output "Hi! How are you today?"

strtoupper() Function :

This function will convert all lower case letters to upper case.

Example:

<?php
$str = "hello!";
echo strtoupper($str);
?>

Output: the above example will output HELLO!

This function changes the first letter in the string to upper case.

Example:

<?php
$str = "hello!";
echo ucfirst($str);
?>

Output : The above function will output Hello!

trim() Function :

This function removes whitespace from the beginning and from the end of the string.

Example:

<?php
$str = " hello! ";
echo trim($str);
?>

Output: The above example will output “hello!”

PHP Regular Expressions Introduction


PHP regular expressions seem to be a quite complicated area especially if you are not an
experienced UNIX user. Historically regular expressions were originally designed to help
working with strings under UNIX systems.

Using regular expressions you can easily find a pattern in a string and/or replace it if you want.
This is a very powerful tool in your hand, but be careful as it is slower than the standard string
manipulation functions.

There are a few common uses for regular expressions. Perhaps the most useful is form
validation. For example, you could use regular expressions to check that an email address
entered into a form uses the correct syntax. We'll consider this specific example later this
chapter.

You could also use them to complete complex search and replace operations within a given body
of text that would not be possible with PHP's standard str_replace function. Yes, the possibilities
are endless!

Using regular expression in PHP

There are two types of regular expression functions included in PHP:

• the ereg functions -- PHP's standard regular expression syntax

• the preg functions, which use a Perl-compatible regular expression syntax

The ereg, eregi, ... are the POSIX versions and preg_match, preg_replace, ... are the Perl
version. It is important that using Perl compatible regular expressions the expression should be
enclosed in the delimiters, a forward slash (/), for example. However this version is more
powerful and faster as well than the POSIX one.

The regular expressions basic syntax

To use regular expressions first you need to learn the syntax of the patterns. We can group the
characters inside a pattern like this:

• Normal characters which match themselves like hello


• Start and end indicators as ^ and $
• Count indicators like +,*,?
• Logical operator like |
• Grouping with {},(),[]

An example pattern to check valid emails looks like this:

Example:

^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$

The code to check the email using Perl compatible regular expression looks like this:

Example:

1. $pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/";
2. $email = "jim@demo.com";
3. if (preg_match($pattern,$email)) echo "Match";
4. else echo "Not match";

It is very similar in case of POSIX extended regular expressions:

Example:

1. $pattern = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$";
2. $email = "jim@demo.com";
3. if (eregi($pattern,$email)) echo "Match";
4. else echo "Not match";

Syntax Reference

This is a quick reference to some of the basic syntax. We've already seen much of it earlier on,
but there are a few new things here that you may find useful.

^ start of string
$ end of string
[a-z] letters a-z inclusive in lower case
[A-Z] letters A-Z inclusive in upper case
[0-9] numbers 0-9 inclusive
[^0-9] no occurrences of numbers 0-9 inclusive
? zero or one of the preceding character(s)
* zero or more of preceding character(s)
+ one or more of preceding character(s)
{2} 2 of preceding character(s)
{2,} 2 or more of preceding character(s)
{2,4} 2 -- 4 of preceding character(s)
. any character
(a|b) a OR b
s empty space (known as whitespace)
Operators
This chapter discusses about operators available in PHP and how operators can be used in
program.

PHP – Operators

In PHP, there are four types of operators available, namely Arithmetic operators, assignment
operator, comparison operators and logical operators.

Arithmetic operators

Following table shows you what are the arithmetic operators and for what purpose they are used.

Operator Purpose
+ Addition
_ Subtraction

* Multiplication

/ Division

% Modulus (reminder of division)

++ Increment

-- Decrement

Example

<?php

$n = 10;
$n1=101;
$n2= $n + $n1; //addition
echo "Addition of $n and $n1 is " . $n2;
echo "<BR>";
$n3 = $n1 - $n; //subtraction
echo "Subtraction of $n from $n1 is " . $n3;
echo "<BR>";
$n4 = $n * $n1; //Multiplication
echo "Multiplication of $n and $n1 is " . $n4;
echo "<BR>";
$n5 = $n1 / $n; //Division
echo "Division of $n1 by $n is ". $n5;
echo "<BR>";
$n6 = $n1 % $n; //Modulus
echo "Modulus of $n1 by $n is ". $n6;
echo "<BR>";

$n=10;
$n++;
echo $n;
echo "<BR>";

$n1=101;
$n1++;
echo $n1;
echo "<BR>";

?>

Output

Addition of 10 and 101 is 111


Subtraction of 10 from 101 is 91
Multiplication of 10 and 101 is 1010
Division of 101 by 10 is 10.1
Modulus of 101 by 10 is 1
11
102

Assignment operator

The basic assignment operator is “=”, usually we think this operator as “equals to”, but it is not
working in that way.
For example, x = y means we assign the value of y to that means value of right operand to x, that
is left operand. Say we assume y is 44, then if we make a statement x = y, means that we assign
the value of 44 to x.

Let us see this in the following example.

Example

<?php

$y = 44;

$x = $y; //we assign the value of y to x

echo "The value of $"."x is ". $x;

echo "<BR>";

?>

Output

The value of $x is 44

Comparison operators

Comparison operator compares one value with another value. There are six comparison operators
as shown in the following table.

Operator Meaning
== is equal to

!= is not equal to

> is greater than

< is less than


>= is greater than or equal to

<= is less than or equal to

Let us see how does it work in the following example.

Examples

10 < 12 //less than operator

12 > 10 //greater than operator

13 >= 11 //greater than or equal to

11 <= 13 //less than or equal to

11 == 11 //is equal to

12 != 14 //is not equal to

Mosty comparison operators used with conditional statements which we will be discussing in the
next chapter.

Examples

<?php

$a= 5;

$b = 10;

if ( $a != $b) //is not equal to


{

echo "Both $". "a and $"."b are not equal";


echo "<BR>";
}

if ( $a <= $b) // is less than or equal to


{

echo "$". "a is less than or equal to $"."b";


echo "<BR>";

if ( $b >= $a) //is greater than or equal to


{

echo "$". "b is greater than or equal to $"."a";


echo "<BR>";
}

if ( $a < $b) //is less than


{

echo "$". "a is less than $"."b";


echo "<BR>";

if ( $b > $a) // is greater than


{

echo "$". "b is greater than $"."a";


echo "<BR>";

$c=15;
$d=15;

if($c == $d) // is equal to


{

echo "Both $". "c and $"."d are equal";


}

?>

Output

Both $a and $b are not equal


$a is less than or equal to $b
$b is greater than or equal to $a
$a is less than $b
$b is greater than $a
Both $c and $d are equal

Logical operators

Logical operators are used to check a statement true or false. There are three logical operators as
shown in the following table.

Operator Meaning
&& And

|| or

! not

&& Operator (and operator)

&& operator checks whether all the values or TRUE.

Example

<?php
$k = 100;

$m = 1000;

if (($k ==100) && ($m==1000))


{
echo “True”;
}

?>

Output
True

|| Operator (or operator)

Or operator checks whether any one of the values is TRUE

Example

<?php
$x =50;

$y = 58;

if (($x == 50) || ($y == 100))


{
echo “True”;
}

?>

Output
True

! operator (not operator)

! operator is also used to validate whether a statement is TRUE or FALSE.

Example

?php

$number = 1000;
if(!($number==999))
{
echo "True";
}

?>

Output
True

Conditional statements
This chapter teaches about the conditional statements in PHP.

Conditional statements
When we do a program, most of the time we need to make a choice, whether a statement is true
or false or we need to execute different actions for different conditions. So we have to use
conditional statements to decide choices.

In PHP are four conditional statements used.

1) If statement

2) If …else statement

3) elseif statement

4) Switch statement

If statement

If statement always start with “if “ and then the condition to be tested in the paranthesis.

If the condition found to be true then the statement or statements immediately following the
condition will be executed. If the condition found to be false then nothing will be occurred.

Syntax:

<?php
if (condition)
{

Statements to be executed;

}
?>

Example:

<?php

$m = 100;
$j = 50;
If ($j ==50 && $m==100)
{
echo “Condition is true”;
}

?>

Output
Condition is true

If .. else statement

Sometimes, we need to check whether the condition is true or false and need to execute certain
statements if the condition is true and if the condition is false then different statemets. If .. else
statement is used for this purpose.

Syntax:

<?php
if (condition)
{

Statements to be executed;

}
else
{

Statements to be executed;

?>

Example:

<?php
$m = 100;
$j = 30;

if($m == 100 && $j==50)


{
echo "Condition is true";
}
else
{

echo "Condition is false";

?>

Output:

Condition is false

elseif statement

elseif statement used to test multiple conditions.

Syntax

<?php
if (condition)
{

Statements to be executed;

}
elseif
{

Statements to be executed;

}
else
{
Statements to be executed;

?>

Example

<?php
$mark = 60;

if ($mark >= 75) {


echo "Passed: Grade A";
echo “<BR>”;
}
elseif ($mark >= 60) {
echo "Passed: Grade B”;
echo “<br />";
}
elseif ($mark >= 45) {
echo "Passed: Grade C”;
echo “<br />";
}
else {
echo "Failed”;
echo “<br />";
}
?>

Output

Passed: Grade B

Switch statement

Switch statement is also used to check against multiple statements like if .. else statement.
A switch statement allows a program to evaluate an expression and attempt to match the
expression's value to a case label. If a match is found, the program executes the associated
statement.

Syntax

<?php

switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_n
[break;]
}
?>

Example

<?php
$car = "BMW";

switch ($car)
{
case "Ferrari" :
echo "car is Ferrari";
break;
case "BMW" :
echo "car is BMW";
break;
case "Mclaren" :
echo "car is Mclaren";
break;
default :
echo "car is some other company";
break;
}
?>

Output

car is BMW

Looping statements
This chapter teaches you about the looping statements.

Looping Statements

In PHP, often you have to execute certain block of statements a number of times, or until a
condition is met. For this purpose, looping statements are used in PHP.

Actully there are two grouping of looping statements are there namely while loop and for loop.
While loops are used when you do not know how many times you have to execute certain block
of statements.

For loops are used to execute certain staements repeatedly for known number of times, i.e you
know how many times loop has to be executed.

While loop

while loop executes the statements number of times until the condition we declare is met.

Syntax:

<?php

while (condition)

statements;
----
----

?>

Example:

<?php
$i= 1;

while ($i<=5)
{

echo "Iam learning PHP";


echo "<BR>";

$i++;
}
?>

Output

Iam learning PHP


Iam learning PHP
Iam learning PHP
Iam learning PHP
Iam learning PHP

The do .. while loop

The do .. while statement is exactly same as while loop except the condition is tested at the end
instead at the beginning. And also in do .. while statement atleast one time the statements are
executed since the condition is tested at the last.

Syntax:

<?php
do
{
statements;
----
----
----
}
while (condition);

?>

Example:

<?php
$k=5;
do {
print"The k is: ".$k."<br>";
$k--;
} while($k>2)
?>

Ouput

The k is: 5
The k is: 4
The k is: 3

for loop

As mentioned earlier for loops are used to execute set of statements known number of times.

Syntax:

<?php

for ( initialize a counter; conditional statement; increment a counter)


{
statements;
----
----
}

?>

As shown in the above syntax the for loop will have an incremental counter and a conditional
statement and loop expression. We can assign a counter and define how many times we want to
execute the loop in conditional statement and what we want to do with the counter in the last part
of the for loop, ie, increment, decrement or multiply etc.

Example:

<?php
$email= array("My ", "residing ", "city ", "is ", "bangalore");
for ($i = 0; $i < sizeof($email);$i++)
{

{
echo $email[$i];
}

?>

Output

My residing city is bangalore

In the above example, we declare an array and output the content of the array. If you look at the
for loop sizeof($email) we are using which is used to tell the lengh of the array $email, that
means 5. So for loop will be executed 5 times, from 0 to 4. That means from 0th element of
$email to 4th element of $email.

foreach loop

foreach loop is used to loop through only array elements.

Syntax:

<?php

foreach (array as value)


{
statements to be executed;
----
----
----
}

?>

Same example we used for the for loop can be done using the foreach loop too.
<?php

$email= array("My ", "residing ", "city ", "is ", "bangalore");

foreach($email as $value)
{

echo $value;

?>

Output

My residing city is bangalore

We will see one more example for foreach loop.

Example

<?php

$myvalues = array(100,200,300,400,500,600,700,800,900);

foreach ($myvalues as $value) {

echo " $value ";

}
?>

Output

100 200 300 400 500 600 700 800 900


Functions
This chapter teaches about functions.

While we do programming, we realize that certain part of code we require again and again either
in the same file or may be in some other file in the future. It is not wise to write the same code
again and again from scratch. Instead of that we can declare the code that we want to use it again
in the function and just we have to call that function wherever we need that code. Functions help
us to reuse the code we have written.

Functions used to help us to write error-reduced, fast and reliable code.

Syntax
function function-name()
{

//code to be executed;

----
----

The function code block starts with a curly brace, and ends with a curly brace as shown above.

Calling a function

After we declare a function, we should be able to use that by calling the function.

Syntax

function-name();

We will look at a simple example how we can declare a function and how we can use that
function.

Example

<?php

function myfunction()
{

echo "Hi, im using function";

myfunction();

?>

Output
Hi, im using function
Function with arguments

We can use function with arguments. That means we can pass variables into function and operate
on those variables. There is no limit of passing arguments. Each argument is separated by a
comma as explained below.

Syntax

function function-name(argument1, argument2 ……. )


{

//code to be executed;

----
----

While calling the function you should use as follows:

function-name(argument1,argument2 …..);

Example

<?php

function arithmetic($a,$b)
{
$c = $a+$b;
echo "Addition of $a and $b is ". $c;
echo "<BR>";

$d = $a * $b;
echo "Multiplication of $a and $b is ". $d;
echo "<BR>";

$e = $a - $b;
echo "Subtraction of $b from $a is ". $e;
echo "<BR>";

}
arithmetic(50,40);

?>

Output

Addition of 50 and 40 is 90
Multiplication of 50 and 40 is 2000
Subtraction of 40 from 50 is 10

In the above example we pass two variables as arguments in function and process those
variables.

Example

<?php

function Table($text)
{
echo "<table border=1><tr>";

echo "<td>$text</td>";

echo "</tr></table>";

Table("Iam learning functions");


?>

Output

Iam learning functions

Function returning value

Sometimes, you might not want your function to automatically display the result. Sometimes you
might just want the function to return the result to you so that you can use it for your own
programmatical purposes. That way, it's your choice whether you display it to the user, or do
something else with the result.
Function can return any one value using return keyword.

Example

<?php
function sum($number1,$number2)
{
$total = $number1 + $number2;
return $total;
}

echo sum(100,100.40);
?>

Output

200.4

if you look at the above example, we are using two arguments and we are adding those two
arguments and storing in a variable. Then we use return keyword and return that variable.

Example

<?php
function multiplication($number1,$number2)
{
$total = $number1 * $number2;
return $total;
}
$multiply=multiplication(30,60);
echo $multiply;
?>

Output

1800
Arrays

Introduction to Arrays

An array can store more than one value. While a variable can hold a single piece of data, an array
can store multiple data using a single variable. Each element in the array has its own ID so that it
can be easily accessed.

PHP Array Syntax: Create an Array

Language-construct array () is used to create an array in PHP. See example below

array( [key =>] value


,…
)

key: key may be an integer or string


value: A value can be of any PHP type
Examples

The following lines of code initialize an array and then add four elements to the array.

$cities= array ();


$cities[0]= ‘Bangalore’;
$cities[1] = ‘Delhi’;
$cities[2]= ‘ Mumbai’;
$cities[3] = ‘Hyderabad’;

The first line of code above is actually optional as the second line will create the array if one
does not already exist. However, it is a better coding practice to explicitly initialize the array.
The $cities array could also be created in a single line as follows.

$cities = array ('Bangalore','Delhi','Mumbai','Hyderabad');

There are three different kinds of arrays:

• Indexed array
• Associative array
• Multidimensional array

Indexed Arrays

Indexed arrays are similar to tables with a single column. An indexed array can contain zero or
more elements, it can store multiple data. In PHP, like in many programming languages, the first
element of an array is in the "zeroeth" position. An array with no elements has a zero length.

There are different ways to create an Indexed array. Below listed are two examples.

Example 1
In this example the ID key is automatically assigned:

$cities = array("Bangalore","Mumbai","Delhi");

Example 2
In this example we assign the ID key manually:

$cities[0] = "Bangalore";
$cities[1] = "Mumbai";
$cities[2] = "Delhi";

The ID keys can be used in a script:


<?php

$cities[0] = "Bangalore";
$cities [1] = "Mumbai";
$cities [2] = "Delhi";
echo $cities[1] . ", " . $cities[2] .
" and ". $cities[0] . "are Indian Cities";

?>

Output of above code will be:

Mumbai, Delhi and Bangalore are Indian Cities.

Associative Arrays

Whereas indexed arrays are indexed numerically, associative arrays are indexed using names.
When we want to store elements in array with some meaningful association other than numbers,
we use associative array. With associative arrays we can use the values as keys and assign values
to them.

For example, let’s say we want to store our employee's job titles in an array. Using numeric
wouldn't be too useful. Instead, we would use an associative array to associate each employee's
name to its job title. Let's have a look at examples below.

Creating an Associative Array

There are two ways to create an associative array. Below are two examples.

Example 1:

<?php

$employee_title["Ram"] = "Owner";
$employee_title["Sunil"] = "Manager";
$employee_title["Ali"] = "Cashier";

echo "Sunil is the ".$employee_title["Sunil"];

?>

Example 2:

<?php
$employee_names = array("Ram" => "Owner", "Sunil" => "Manager", "Ali" => "Cashier");

echo "Sunil is the ".$employee_title["Sunil"];

?>

In both examples above, we created an associative array $employee_title and output of both the
examples is “Sunil is the Manager".

Multidimensional Arrays

In a multidimensional 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. Consider the Employees Table/Matrix
below.

Employees Table/Matrix
name title salary
employee 1 Ram Owner 80,000
employee 2 Sunil Manager 35,000
employee 3 Ali Cashier 15,000

Let's look at the examples below to see how we would do that.

Creating Multidimensional Array in PHP

There are two ways to create a multidimensional array. Let’s look at the examples below.

Example 1

<?php

$employees["employee 1"]["name"] = "Ram";


$employees["employee 1"]["title"] = "Owner";
$employees["employee 1"]["salary"] = "80,000";

$employees["employee 2"]["name"] = "Sunil";


$employees["employee 2"]["title"] = "Manager";
$employees["employee 2"]["salary"] = "35,000";

$employees["employee 3"]["name"] = "Ali";


$employees["employee 3"]["title"] = "Cashier";
$employees["employee 3"]["salary"] = "15,000";

echo $employees["employee 2"]["name"].


" is the ".$employees["employee 2"]["title"].
" and he earns ".$employees["employee 2"]["salary"].
" a year.";

?>

The above code creates a multidimensional array name employees and outputs "Sunil is the
Manager and he earns 35,000 a year".

Example 2

<?php

$employees = array
(
"employee 1" => array
(
"name" => "Ram",
"title" => "Owner",
"salary" => "80,000",
),

"employee 2" => array


(
"name" => "Sunil",
"title" => "Manager",
"salary" => "35,000",
),

"employee 3" => array


(
"name" => "Ali",
"title" => "Cashier",
"salary" => "15,000",
)
);

echo $employees["employee 1"]["name"].


" is the ".$employees["employee 1"]["title"].
" and he earns ".$employees["employee 1"]["salary"].
" a year.";

?>

The above code creates a multidimensional array name employees and outputs "Ram is the
Owner and he earns 80,000 a year.

Printing PHP Arrays

To print the results of an array you can use the PHP function print_r(). See example below.

<?php

$employee_title["Ram"] = "Owner";
$employee_title["Sunil"] = "Manager";
$employee_title["Ali"] = "Cashier";

print_r($employee_title);

?>

The array result will print out as follow...


Array
(
[Ram] => Owner
[Sunil] => Manager
[Ali] => Cashier
)

Summary
So, in this section we covered an important lesson on arrays. You will find yourself using arrays
a lot because it’s the easiest and useful way of storing values
PHP Forms
This chapter demonstrates how to use PHP forms. In this chapter you will find detailed
information from the form basics to advanced form processing.
Creating an HTML form
Forms are a vital tool, to receive information from the user, such as: their name, email
address, credit card, etc. A form will take input from the viewer and depending on your
needs, you may store that data into a file, place an order, gather user statistics, register the
person to your web forum, or maybe subscribe them to your weekly newsletter.
Below is an example of a Form.
<html>

<body>

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

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


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

<input type="submit" />

</form>

</body>

</html>

The HTML page above contains two input fields and a submit button. When the user fills
in this form and click on the submit button, the form data is sent to the page called
"index.php" file.
The "index.php" file looks like this:
<html>

<body>

Hello <?php echo $_POST["name"]; ?>.<br />

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

</body>

</html>

Output of the above script may be :


Welcome Mike.
You are 25 years old.
Form Handling
User input should be validated whenever possible. Client side validation is faster, and

will reduce server load.

However, any site that gets enough traffic to worry about server resources may also need

to worry about site security. You should always use server side validation if the form

accesses 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.

Values from the form can be collected using one of the three methods. $_GET,

$_REQUEST and $_POST.

$_GET Variable

The $_GET variable is an array of variable names and values sent by the HTTP GET

method.

The $_GET variable is used to collect values from a form 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 it has limits on the amount of information to

send (max. 100 characters).

Example

<form action="index.php" method="get">

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

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

<input type="submit" />

</form>
When the user clicks the "Submit" button, the URL sent could look something like this:
http://www.siliconindia.com/index.php?name=MIke&age=25
The "index.php" file can now use the $_GET variable to catch the form data.

Hello <?php echo $_GET["name"]; ?>.<br />

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


Why use $_GET?

• When using the $_GET variable all variable names and values are displayed in

the URL. So 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.

• The HTTP GET method is not suitable on large variable values; the value cannot

exceed 100 characters.

$_POST Variable

$_POST variable is an array of variable names and values sent by the HTTP POST

method.

The $_POST variable is used to collect values from a form 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.

Example:

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

Enter your name: <input type="text" name="name" />


Enter your age: <input type="text" name="age" />

<input type="submit" />

</form>

When user clicks the “submit” button, url will not contain any form data, and it may look like this

http://www.siliconindia.com/index.php

The "index.php" file can now use the $_POST variable to catch the form data

Hello <?php echo $_POST["name"]; ?>.<br />

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

Why use $_POST?

• Variables sent with HTTP POST are not shown in the URL
• Variables have no length limit

$_REQUEST Variable

PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and

$_COOKIE.

The PHP $_REQUEST variable can be used to get the result from form data sent with

both the GET and POST methods.


Example

Welcome <?php echo $_REQUEST["name"]; ?>.<br />

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

Summary

So, in this section we covered an important lesson on HTML Forms. We learned how to

create a form, and how to catch the form data using $_POST, $_GET and $_REQUEST

method.

Opening a File

The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and
the Second parameter specifies in which mode the file should be opened:

Example:

<html>
<body>
<?php
$file=fopen("myfile.txt","r");
?>
</body>
</html>

The above function will open the file myfile.txt file in read mode.

The file may be opened in one of the following modes:

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if
it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it
doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already
exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already
exists

Example
The following example generates a message if the fopen() function is unable to
open the specified file:

<?php
$file=fopen("myfile.txt","r") or exit("File not found!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

Output:

If the file myfile.txt is not found, then example will output,


File not found!

Closing a File
fclose() function is used to close an open file:

Example:

<?php
$file = fopen("myfile.txt","r"); ///myfile.txt is opened
//code to be executed
fclose($file); //this function will close the file
?>

Reading a File

We can read a file either line by line or read single character from a file.

The fgets() function is used to read a single line from a file.

Example:
The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen("myfile.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>

The fgetc() function is used to read a single character from a file.

Example:
The example below reads a file character by character, until the end of file is
reached:

<?php
$file=fopen("myfile.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

Writing to a file:

The fwrite() function is used to write to a file. The fwrite function allows data to be
written to any type of file. Fwrite's first parameter is the file handle and its second
parameter contains string of data that is to be written. Just give the function those
two bits of information and you're good to go! Below is an example of writing to a
file using fwrite function.

Example:

<?php
$file_name = "myfile.txt";
$file_pointer = fopen($file_name, "w+");
// "w+" is the write mode, or the action we're going to perform on the file
// "w+" mode clears the existing file content to 0 bytes
fwrite($file_pointer, "PHP is power ");
// write something to the file
fclose($file_pointer);
print "data written to file successfully";
?>

As you see whenever we open the file in write mode the previous contents are
getting truncated. If you want to keep the previous file contents, then you have to
open the file in "append" mode. To open the file in append mode, you have to use
“a”

Printing all the records from a file

Now, if you want to print all the contents from a file, then the code will be

<?php
$filename = "myfile.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp))
{ $line = fgets($fp);
print "$line<br>";
}
fclose($fp);
?>

The above example will open the file myfile.txt, and print all the contents of the
file, line by line.

PHP Cookies

Introduction to php cookie

Cookie is a small file which sits on user’s computer. Each time that user requests a page or goes
to a webpage, all cookie information is sent too. This is used to identify who you are.
Cookies allow the webmaster to store information about the site visitor on their computer to be
accessed again the next time they visit. One common use of cookies is to store your username
and password on your computer so you don't need to login again each time you visit a website.
Cookies can also store other things such as your name, last visit, shopping cart contents, etc.

Creating Cookie

The setcookie() function is used to set a cookie, means save the cookie on the user system.

Syntax

setcookie($name, $value, $expire, $path, $domain, $secure)

$name - name of the cookie. Example: "username"

$value - value of the cookie. Example: "ramesh"

$expire - time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600".
Cookie is set to expire after one hour.

$path - path on the server where cookie will be available.

For example, if the path is set to "/", the cookie will be available through out the whole site. If
the cookie is set to say "/news/", the cookie will only be available under /news/ and all its sub-
directories.
If no path is given, cookie in created under the current directory.

$domain - domain where cookie will be available. Instead of path you can use domain settings.

For example, if the domian is set to ".siliconindia.com", the cookie will be available within the
domain and all its sub-domains, example news.yourdomain.com.

If the cookie is set say "www.siliconindia.com" the cookie will be available under all www sub-
domains, example " www.siliconindia.com/career"

$secure - true if cookie is being set over a secure "https" server, false otherwise, Default value is
false.

Note :All the arguments except the name argument are optional.

The setcookie() function must appear before the <html> tag.

Example 1

In the example below, we will create a cookie named "userid" and assign the value
"X12AS67" to it. We also specify that the cookie should expire after one hour:

<?php

setcookie("userid", "X12AS67", time()+3600);

?>

<html>
How to check if cookie is set or not?

In the following example we use the isset() function to find out if a cookie has been set:

<html>

<body>

<?php

if (isset($_COOKIE["username"]))

echo "Welcome " . $_COOKIE["username"] . "!<br />";

else

echo "Welcome guest!<br />";

?>

</body>

</html>

In above example, we are checking if the variable $_COOKIE[‘username’] is set or not, if


cookie is set (cookie is available on user system), we are displaying Welcome username, for ex if
the usename is ramesh, then Welcome Ramesh

If cookie is not set, we are displaying Welcome guest as generic message.


Retrieving and deleting the set cookie

How to retrieve a set cookie value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we first set cookie in cookie1.php and then, we retrieve the value of the
cookie named "userid" in cookie2.php and display it on same page.

Cookie1.php

<?php

setcookie("userid", "X12AS67", time()+3600);

echo "<a href ='cookie2.php'>Click here to see the cookie</a>";

?>

Cookie2.php

<?php

// Print a cookie

echo "Your userid: ".$_COOKIE["userid"];

?>

Output will be: Your userid: X12AS67.


How to set expiration time for cookies

Following example demonstrates the setting expiration time for cookie. Here we are setting
expiration is 30days.

<?php

$expire=time()+60*60*24*30;

setcookie("username", "john", $expire);

?>

<html>

In above example, we are setting cookie name username having value ‘john’ to 30 days from
current time.

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("user", "", time()-3600);

?>
In above example, we are setting cookie name ‘user’ to empty string and expiration time to 1
hour back from current time.

Cookie Example

Cookie1.php

<?php

$user = $_POST['username'];

$color = $_POST['colorchoice'];

$self = $_SERVER['PHP_SELF'];

if( ( $user != null ) and ( $color != null ) )

setcookie( "firstname", $user , time() + 86400 ); // 24 hours

setcookie( "fontcolor", $color, time() + 86400 );

header( "Location:cookie2.php" );

exit();

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">

<title>siliconindia cookie</title>

</head>

<body>

<h1> siliconindia cookie </h1>

<hr>

<form action ="<?php echo( $self ); ?>" method = "post">

Please enter your first name:

<input type = "text" name = "username "><br><br>

Please choose your favorite font color:<br>

<input type = "radio" name = " colorchoice " value = "Red">Red

<input type = "radio" name = " colorchoice " value = "Green">Green


<input type = "radio" name = " colorchoice " value = "Blue">Blue

<br><br>

<input type = "submit" value = "submit">

</form>

<br/>

<hr>

</body>

</html>

</html>

output will be:

siliconindia cookie

Please enter your first name:

Please choose your favorite font color:

Red Green Blue

Cookie2.php
<?php

if (isset($_COOKIE['firstname']))

$user = $_COOKIE['firstname'];

$color= $_COOKIE['fontcolor'];

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">

<title>siliconindia</title>

</head>

<body>

<h1> siliconindia cookie</h1>

<hr>

<h2>Hello: <?php echo( $user ); ?> </h2>

<h2>Your color: <?php echo( $color ); ?> </h2>


</body>

</html>

Output will be :

siliconindia cookie

________________________________________

Hello: Ramesh

Your color: Green

In above example, If we run cookie1.php, we will see form, where user can enter his name in the
text box and select colour by three radio button. Once user submit the form after filling all
details, we get the username and colour by $_POST['username'], $_POST['colorchoice']. Then
we set those variables in the cookie

firstname , fontcolor . After setting cookie, we redirect user to cookie2.php page, where we
retrieve these cookie and display.
PHP Sessions

Introduction to Session

A PHP session variable is used to store information about user. Session variables hold
information about one single user and make it available to all pages in one application.
When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't maintain state. HTTP is
stateless protocol.

A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may want
to store the data in a database.

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.

Starting and deleting PHP session

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>

<html>

<body>

</body>

</html>

The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.

Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable.
This variable will be available after starting session only.

Example1.php

<?php

session_start();

// store session data

$_SESSION['itemno']=1;

?>

<html>

<body>

<?php
//retrieve session data

echo "Item in cart=". $_SESSION['itemno'];

?>

</body>

</html>

Output:

Item in cart =1

In the example below, we create a simple Item number counter, which will increase at every
refresh . The isset() function checks if the "itemno" variable has already been set. If " itemno"
has been set, we can increment our counter. If "itemno" doesn't exist, we create a "itemno"
variable, and set it to 1:

Example2.php

<?php

session_start();

if(isset($_SESSION['itemno']))

$_SESSION['itemno']=$_SESSION['itemno']+1;

else
$_SESSION['itemno']=1;

echo "Itemno.=". $_SESSION[' itemno'];

?>

Output: Itemno= 6

Above output will come, if we refresh page six time.

Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php

unset($_SESSION['itemno']);

?>

You can also completely destroy the session by calling the session_destroy() function:

<?php

session_destroy();

?>

Note: session_destroy() will reset your session and you will lose all your stored session data.
Session Example

Session1.php

<?php

session_start();

?>

<html>

<head>

<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">

<title>SiliconIndia</title>

</head>

<body>

<h1>Siliconindia (page 1)</h1>

<hr>

<h3>PHPSESSID = <?php echo session_id(); ?></h3>

<hr>
<h2>Click the next page and see number of visits during this visit.</h2>

<a href="session2.php?<?php echo( SID ); ?>">Next page</a>

</body>

</html>

output:

Siliconindia (page 1)

________________________________________

PHPSESSID = 9tc0ifhkid937o5bi44k7u2rp4

________________________________________

Click the next page and see number of visits during this visit.

Next page

Session2.php

<?php

session_start();

($_SESSION['count']) ? $_SESSION['count']++ : $_SESSION['count'] = 1;

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">

<title>siliconindia</title>

</head>

<body>

<h1>siliconindia (page 2)</h1>

<hr>

<h3>PHPSESSID = <?php echo session_id(); ?></h3>

<hr>

<h2>You have been here <?php echo( $_SESSION['count'] ); ?> times in this session.</h2>

<a href="session1.php?<?php echo( SID ); ?>">Previous page</a>

</body>

</html>

</html>

Output:

siliconindia (page 2)

________________________________________
PHPSESSID = 9tc0ifhkid937o5bi44k7u2rp4

________________________________________

You have been here 6 times in this session.

Here in this example we are starting session on first page and displaying sessionid, when we
click on the next link it is going to next page and increment the session count . Each time we go
to next page, it shows the incremented count. We can see both page session id are same. So both
page are in session.

Visibility, Scope Resolution Operator, Static


Keywords

Visibility
The visibility of a property or method can be defined by prefixing
the declaration with the keywords: public, protected or
private. Public declared items can be accessed everywhere.
Protected limits access to inherited and parent classes (and to
the class that defines the item). Private limits visibility only to
the class that defines the item.

Members Visibility

Class members must be defined with public, private, or protected.

Example #1 Member declaration

<?php

/**

* Define MyClass

*/

class MyClass

public $public = 'Public';

protected $protected = 'Protected';

private $private = 'Private';

function printHello()
{

echo $this->public;

echo $this->protected;

echo $this->private;

$obj = new MyClass();

echo $obj->public; // Works

echo $obj->protected; // Fatal Error

echo $obj->private; // Fatal Error

$obj->printHello(); // Shows Public, Protected and Private

/**

* Define MyClass2

*/

class MyClass2 extends MyClass

{
// We can redeclare the public and protected method, but not
private

protected $protected = 'Protected2';

function printHello()

echo $this->public;

echo $this->protected;

echo $this->private;

$obj2 = new MyClass2();

echo $obj2->public; // Works

echo $obj2->private; // Undefined

echo $obj2->protected; // Fatal Error

$obj2->printHello(); // Shows Public, Protected2, Undefined

?>
Method Visibility

Class methods must be defined with public, private, or protected.


Methods without any declaration are defined as public.

Example #2 Method Declaration

<?php

/**

* Define MyClass

*/

class MyClass

// Declare a public constructor

public function __construct() { }

// Declare a public method

public function MyPublic() { }


// Declare a protected method

protected function MyProtected() { }

// Declare a private method

private function MyPrivate() { }

// This is public

function fundumethod()

$this->MyPublic();

$this->MyProtected();

$this->MyPrivate();

$myclass = new MyClass;


$myclass->MyPublic(); // Works

$myclass->MyProtected(); // Fatal Error

$myclass->MyPrivate(); // Fatal Error

$myclass-> fundumethod(); // Public, Protected and Private work

/**

* Define MyClass2

*/

class MyClass2 extends MyClass

// This is public

function fundumethod2()

$this->MyPublic();

$this->MyProtected();
$this->MyPrivate();

$myclass2 = new MyClass2;

$myclass2->MyPublic(); // Works

$myclass2-> fundumethod2();

Scope Resolution Operator (::)

The Scope Resolution Operator or in simpler terms, the double colon, is a token that
allows access to static, constant, and overridden members or methods of a class.

When referencing these items from outside the class definition, use the name of the
class.
Example #1 :: from outside the class definition

<?php

class MyClass {

const CONST_VALUE = 'A constant value';

$classname = 'MyClass';
echo $classname::CONST_VALUE;

echo MyClass::CONST_VALUE;

?>

Two special keywords self and parent are used to access members or methods from
inside the class definition.

Example #2 :: from inside the class definition

<?php

class OtherClass extends MyClass


{

public static $my_static = 'static var';

public static function doubleColon() {

echo parent::CONST_VALUE . " ";

echo self::$my_static . " ";


}

$classname = 'OtherClass';

echo $classname::doubleColon();

OtherClass::doubleColon();
?>

Example #3 Calling a parent's method

When an extending class overrides the parents definition of a method, PHP will not
call the parent's method. It's up to the extended class on whether or not the
parent's method is called.
<?php

class MyClass

protected function myFunc() {

echo "MyClass::myFunc() ";

}
}

class OtherClass extends MyClass

// Override parent's definition

public function myFunc()

{
// But still call the parent function

parent::myFunc();

echo "OtherClass::myFunc() ";

}
$class = new OtherClass();

$class->myFunc();

?>

Static Keywords:

Declaring class members or methods as static makes them accessible without


needing an instantiation of the class. A member declared as static can not be
accessed with an instantiated class object (though a static method can).

Example #1 Static member example


<?php

class First

public static $my_static = 'first';

public function staticValue() {


return self::$my_static;

class Bar extends First

public function fooStatic() {


return parent::$my_static;

print First::$my_static." ";


$first = new First();

print $first->staticValue()." ";

print $first->my_static." "; // Undefined "Property" my_static

print Bar::$my_static." ";


$bar = new Bar();

print $bar->fooStatic()." ";

?>

Example #2 Static method example

<?php

class First {
public static function aStaticMethod() {

// ...

First::aStaticMethod();

?>
Inheritance
This chapter teaches about the inheritance
Inheritance

Concept of inheritance

Inheritance is the mechanism of extending an already existing class. By inheritance we create a


new class with all functionalities as an existing class and we add new functionalities to the new
class. This way we extend the existing class without modifying its code.

New class is called “sub class” and the existing class is called as “super class”.

For inheritance we need at least on existing class. We create a new class using the keyword
“extends”.

In the following example i will explain a class called “company” and how it can be inherited. We
will have properties for this class like name, address, phone as class members. I will extend this
class and create a class “company1”. This class has all properties and functions of class
“company”, because it is inherited from it. And i will add more properties in this class.

Two very important keywords in OOPS are $this and parent. We access class members and
properties as follows.
$this->name;
$this is a reference to the calling object and we use it to access class members.
parent is a keyword which we use to access members of a parent class.
We access them with:
parent::function();

Example:

<?php
class Company {
var $name;
var $address;
var $phone;
function companyInfo()
{
echo $this->name . "<BR>";
echo $this->address . "<BR>";
echo $this->phone . "<BR>";
}
}
class Company1 extends Company {
var $category;
var $website;
var $ceo;
function companyInfo1()
{
parent::companyInfo();
echo $this->category . "<BR>";
echo $this->website . "<BR>";
echo $this->ceo . "<BR>";
}
}
$comp1 = new Company1();
$comp1->name = "MAIA Intelligence";
$comp1->address = "319, Sector I, Building No. 2, 3rd
Floor, Mumbai";
$comp1->phone = "022-456789";
$comp1->category = "Software";
$comp1->website = "http://maia.com";
$comp1->ceo="Raja";
$comp1->companyInfo1();
?>

Output
MAIA Intelligence
319, Sector I, Building No. 2, 3rd Floor, Mumbai
022-456789
Software
http://maia.com
Raja

In the above example, we have defined a class “Company” to display name, address and phone.
And in the second class “Company1” we extended the “Company” class and we have added
three more details, category, website and ceo.
While creating object, we have used derived class object and displayed all the 6 details, since it
has been inherited from base class it echoed all the 6 details.
“class Company1 extends Company”, this line tells that we are creating a class “Company1”
which is inheriting from the class “Company”.
parent::companyInfo(); this line declares that we are calling base class’s companyInfo() function
in the new class.
Smarty Installation
This is a simple guide to get Smarty setup and running quickly. The online documentation
includes a very thorough explanation of a Smarty installation. This guide is meant to be a quick
and painless way of getting Smarty working,
and nothing more. The guide assumes you are familiar with the UNIX system
environment. Windows users will need to make adjustments where necessary.

Smarty Installation

This document assumes that your webserver and php5 is running.


Download Smarty - http://smarty.net

Extract files, rename Smarty.x.x.x to smarty (suggest to put OUTSIDE of your www root!)

Create a folder Smarty in www and setup two folders namely “templates” and config in it.
Example c:\wamp\www\smarty\templates
Example c:\wamp\www\smarty\configs

In folder c:Smarty (created in step 1)setup two folders namely “templates_c” and “cache”.
Example: c:\Smarty\templates_c
Example: c:\Smarty\cache

Run phpinfo.php to find php.ini file. In this edit include_path, and edit it as c:\smarty\libs”

Restart Apache after changing php.ini file setting.

Create file “index.php” and place it in www folder

//start index.php
<?php
require('smarty_connect.php');
$smarty= new smarty_connect();
$smarty->assign('name','rajan');
$smarty->display('index.tpl');
?>
Create file “Smarty_connect.php” place this in c:smartylibs folder.
Smarty_connect.php

//start smarty_connect.php
<?php

//load Smarty library


require('Smarty.class.php');
class smarty_connect extends Smarty
{
function smarty_connect()
{
$smarty=new Smarty();
//End //Class Constructor.
//These automatically get set with each new instance.
$this->Smarty();
$this->template_dir='C:\wamp\www\smarty\templates';
$this->config_dir='C:\wamp\www\smarty\configs';
$this->compile_dir='C:\Smarty\templates_c';
$this->cache_dir='C:\Smarty\cache';
//This->assign('appname', 'Intranet');
}
}
?>
//end smarty_connect.php

Create “index.tpl” put in templates folder

index.tpl

//start index.tpl

<html>
<body>
Hello, {$name}
</body>
</html>

// index.tpl

Start your local host and run index.php and you can see the result as “hello, Rajan”
Your setup is complete. Experience new creativity with Smarty.

Note:
1. if getting error “smarty.class.php not found” check address on php.ini
2. “index.tpl not found” check whether it is saved with extension.tpl or check address on
Smarty_connect.php
3. If any other error unzip file once again.
4. Check folder name once again.
Introduction to smarty and smarty loops

What is Smarty?

Smarty is a template engine for PHP. It separates business logic with presentation logic.It is very
usefull in case where we have different team of Designer and Developer. By using smarty,
designer can easily change user interface(Template file) without touching any code in business
logic(PHP file) and Developer can also modify logic of code without touching code of templates
to display, unless it doesn’t change the variable used to display the data.

Extension of template file is ‘.tpl’.

We write presentation logic in the template file and business logic in the PHP files

We save template file under template folder under document root, path of template folder will be
defined in the smarty configurational file.

For example lets assume Magazine.php file is the file containing business logic and Magazine.tpl
contains presentation logic.

Example of smarty.

Magazine.php

<?php

require('Smarty_connect.php');
$smarty = new Smarty_connect();

$headline = ‘India won’;

$author = ‘Rajan’;

$smarty->assign('headline',$headline);

$smarty->assign('author',$author);

$smarty->display(‘magazine.tpl’);

?>

Magazine.tpl

<html>

<head><title>

Magazine page

</title></head>

<body>

<b>Todays’ Headline</b>: <font color=”red”>{$headline}</font>

<br>

By {$author}

</body></html>

Todays’ Headline: India won

By Rajan
Business Logic in above example: Magazine.php file assign the value to the variable (headline
and author) used to display the content in the template file.

We are requiring smarty_si.php in the PHP file. This file is having class which contains the
configuration information of smarty. $smarty is the object of smarty class. Through $smarty
object we are accessing assign method of smarty to assign the value to the smarty variable and
display method to tell the PHP parser which template file it has to look to display the content of
this PHP file.

Presentation Logic in above example: Magazine.tpl file will display the variable in well
formatted way. We are using {$variable} to display smarty variable.

So as we explained earlier if the designer want to change the color of the headline variable from
red to blue, he can go and change the color in magazine template file without making any change
in the php file.

So here application logic is written in the magazine.php and presentation logic is written in
magazine.tpl.

Smarty loops

In this section, we are describing two types of smarty loops. Section and Foreach loop

{section},{sectionelse}
A {section} loop is used for looping over arrays of data. There are many attributes are g

• Required attributes are name and loop.

• The name of the {section} can be anything you like, made up of letters, numbers and
underscores, like PHP variables.

• {section}'s can be nested, and the nested {section} names must be unique from each
other.

• The loop attribute, usually an array of values, determines the number of times the
{section} will loop. You can also pass an integer as the loop value.

• When printing a variable within a {section}, the {section} name must be given next to
variable name within [brackets].

• {sectionelse} is executed when there are no values in the loop variable.

• A {section} also has its own variables that handle {section} properties. These properties
are accessible as: {$smarty.section.name.property} where "name" is the attribute name.

• {section} properties are index, index_prev, index_next, iteration, first, last,

Example:

PHP file

<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$data = array(1000,1001,1002);

$smarty->assign('custid',$data);

$smarty->display('smartytest.tpl');
?>

The template that outputs the array

{* this example will print out all the values of the $custid array *}

{section name=customer loop=$custid}

id: {$custid[customer]}<br />

{/section}

The above example will output:

1 0 id: 1000

2 1 id: 1001

3 2 id: 1002
Example for sectionelse

{sectionelse} is executed when there are no values in the loop variable.

<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$data = '';

$smarty->assign('custid',$data);

$smarty->display('smartytest.tpl');

?>

{section name=customer loop=$custid}

id: {$custid[customer]}<br />

{sectionelse}

No data

{/section}

Output:

No data
In above example, we can see variable data is empty, so sectionelse will execute and we get
output No data.

Most Commonly used Properties:

Index: index contains the current array index, starting with zero or the start attribute if given. It
increments by one or by the step attribute if given.

Example for index properties.

For Your Information: $custid[customer.index] and $custid[customer] are identical.

{section name=customer loop=$custid}

{$smarty.section.customer.index} id: {$custid[customer]}<br> {/section}

The above example will output:

0 id: 1000

1 id: 1001

2 id: 1002

Index_prev: index_prev is the previous loop index. On the first loop, this is set to -1.
Index_next: It is the next loop index. On the last loop, this is still one more than the current
index, respecting the setting of the step attribute, if given.

Example for index_prev and index_next

<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$data = array(101,102,103,104,105);

$smarty->assign('rows',$data);

$smarty->display('smartytest.tpl');

?>

Template to output the above array in a table

<table>

<tr>

<th>index</th><th>id</th>

<th>index_prev</th><th>prev_id</th>

<th>index_next</th><th>next_id</th>

</tr>

{section name=row loop=$rows}

<tr>

<td>{$smarty.section.row.index}</td><td>{$rows[row]}</td>

<td>{$smarty.section.row.index_prev}</td><td>{$rows[row.index_prev]}</td>
<td>{$smarty.section.row.index_next}</td><td>{$rows[row.index_next]}</td>

</tr>

{/section}

</table>

The above example will output a table containing the following:

index id index_prev prev_id index_next next_id

0 101 -1 1 102

1 102 0 101 2 103

2 103 1 102 3 104

3 104 2 103 4 105

4 105 3 104 5
Smarty Variables Modifiers

Smarty modifiers are very good utility. By help of this we can implement some display logic in
smarty templates.

Variable modifiers can be applied to variables or strings. We should specify the value followed
by a | (pipe) and the modifier name. A modifier may accept additional parameters that affect its
behavior. These parameters follow the modifer name and are separated by a : (colon).

There are number of modifiers are provided by smarty. Here we are going to study, which are
used most.

a)capitalize

b)count_characters

c)date_format

d)nl2br

e)truncate

capitalize

It is used to capitalize the first letter of all words in a variable.

For ex:

Captest.php

<?php
require_once('smarty_si.php');

$smarty = new Smarty_si();

$smarty->assign('articleTitle', ‘pankaj);

$smarty->display(‘Captest.tpl');

?>

Where the template is:

Captest.tpl

{$articleTitle|capitalize}

Result will be

Pankaj

count_characters

It is used to count the number of characters in a variable.

Captest.php
<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$smarty->assign('articleTitle', ‘pankaj);

$smarty->display(‘Captest.tpl');

?>

Where the template is:

Captest.tpl

{$articleTitle|count_characters}

Result will be

date_format

This formats a date and time into the given strftime() format.

Captest.php
<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$datetest = date('YYYY-MM-DD');

$smarty->assign('articleTitle', $datetest);

$smarty->display('Captest.tpl');

?>

Captest.tpl

{$articleTitle|date_format}

Result will be

Jul 25, 2009

nl2br

All "
" line breaks will be converted to html <br /> tags in the given variable.
Captest.php

<?php

require_once('smarty_si.php');

$smarty = new Smarty_si();

$smarty->assign('articleTitle', ‘Hi
Pankaj’);

$smarty->display('Captest.tpl');

?>

Captest.tpl

{$articleTitle|nl2br}

Result will be

Hi</br> Pankaj
Caching in Smarty

Caching is a way of improving a Web page's performance by saving the executed version of a
page as a static file. This allows the server to handle multiple requests for the same page with
only one execution of the underlying PHP script. Caching can be applied to any type of content
provided to the browser by the server but it makes particular sense to use it with templated pages.
Smarty caching refers to a built-in caching that's easy to use.

Setting up cache in Smarty

Enable caching in smarty

First thing you have to do, for setting up caching is by setting $caching = 1 or to 2.

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;

$smarty->display('index.tpl');

?>

With caching enabled, the function call to display('index.tpl') will render the template as usual,
but also saves a copy of its output to a file (a cached copy) in the $cache_dir. On the next call to
display('index.tpl'), the cached copy will be used instead of rendering the template again.

Adjusting the cache expiration or lifetime


Each cached page has a limited lifetime determined by $cache_lifetime. The default value is
3600 seconds i.e. an hour. After that time expires, the cache is regenerated. It is possible to give
individual caches their own expiration time by setting $caching=2. In below example we set
$cache_lifetime per cache.

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 2; // lifetime is per cache

// set the cache_lifetime for index.tpl to 5 minutes

$smarty->cache_lifetime = 300;

$smarty->display('index.tpl');

// set the cache_lifetime for home.tpl to 1 hour

$smarty->cache_lifetime = 3600;

$smarty->display('home.tpl');

// NOTE: the following $cache_lifetime setting will not work when $caching = 2.

// The cache lifetime for home.tpl has already been set

// to 1 hour, and will no longer respect the value of $cache_lifetime.

// The home.tpl cache will still expire after 1 hour.

$smarty->cache_lifetime = 30; // 30 seconds

$smarty->display('home.tpl');
?>

Checking the Cache

The is_cached() function can be used to test if a template has a valid cache or not. If you have a
cached template that requires something like a database fetch, you can use this to skip that
process. Below example shows how to use the is_cached() function.

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;

if(!$smarty->is_cached('index.tpl')) {

// No cache available, do variable assignments here.

$contents = get_database_contents();

$smarty->assign($contents);
}

$smarty->display('index.tpl');

?>
<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;
if(!$smarty->is_cached('index.tpl')) {

// No cache available, do variable assignments here.

$contents = get_database_contents();

$smarty->assign($contents);

$smarty->display('index.tpl');

?>

Clearing the Cache

You can clear all the cache files with the clear_all_cache() function, or individual cache files
and groups with the clear_cache() function. Example below shows how to clear the cache.

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;

// clear only cache for index.tpl

$smarty->clear_cache('index.tpl');

// clear out all cache files

$smarty->clear_all_cache();
$smarty->display('index.tpl');

?>

Create multiple caches per page

You can have multiple cache files for a single call to display() or fetch(). Sometimes it’s
necessary to maintain multiple caches for a single file. Let’s say file where, page 1 content will
be different from page 2 content and so on. In this case, it will be necessary to maintain multiple
cache files. You can do this by passing a $cache_id as the second parameter to the function call
to display () or fetch ().

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;

$my_cache_id = $_GET['article_id'];

$smarty->display('index.tpl', $my_cache_id);

?>

Above, we are passing the variable $my_cache_id to display() as the $cache_id. For each
unique value of $my_cache_id, a separate cache will be generated for index.tpl. In this example,
article_id was passed in the URL and is used as the $cache_id.

Note : Be very cautious when passing values from a client (web browser) into Smarty or any
PHP application. Although the above example of using the article_id from the URL looks handy,
it could have bad consequences. The $cache_id is used to create a directory on the file system, so
if the user decided to pass an extremely large value for article_id, or write a script that sends
random article_id's at a rapid pace, this could possibly cause problems at the server level. Be sure
to sanitize any data passed in before using it. In this instance, maybe you know the article_id has
a length of ten characters and is made up of alpha-numerics only, and must be a valid article_id
in the database. Check for this!

Passing a cache_id to is_cached()

Example:

<?php

require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1;// enable caching

$my_cache_id = $_GET['article_id'];

if(!$smarty->is_cached('index.tpl',$my_cache_id)) {

// No cache available, do variable assignments here.

$contents = get_database_contents();

$smarty->assign($contents);

$smarty->display('index.tpl',$my_cache_id);

?>

You can clear all caches for a particular $cache_id by passing NULL as the first parameter to
clear_cache(). Example below shows how to use this function.

Example:

<?php
require('Smarty.class.php');

$smarty = new Smarty;

$smarty->caching = 1; //enable caching

// clear all caches with "sports" as the $cache_id

$smarty->clear_cache(null,'sports');

$smarty->display('index.tpl','sports');

?>

In the above example, we clear all the caches with “sports” as the cacheid.

You might also like