You are on page 1of 28

PHP

TUTOR
[A Quick Guide for Beginners]

by
S A Shakil
[1]

1. Introduction to PHP
Welcome! Let's start by answering some of the basic questions on PHP and OPEN SOURCE...

1.1 What is PHP?


PHP stands for "PHP: HyperText Preprocessor". PHP is a server side scripting language for making logic driven
websites. Ever wonder how they made that "contact us" form on their site, which sends out emails? Well, they used
PHP. Or, how they made that image upload tool? Well, they used PHP. PHP written scripts can use databases to keep
track of your customer's and visitors activities on your site, send out periodical newsletters to your subscribers,
upload files or images and drive the content on your site dynamically. The possibilities are endless. Yep! PHP is that
powerful. Learning The Basics of PHP will help you tremendously in your Webpage development.

1.2 How PHP Works?


PHP sits between your browser and the web server. When you type in the URL of a PHP website in your
browser, your browser sends out a request to the web server. The web server then calls the PHP script on that page.
The PHP module executes the script, which then sends out the result in the form of HTML back to your browser,
which you see on the screen. Here is a basic PHP diagram which illustrates the process.

1.3 What are PHP benefits?


PHP is a free open source language. Best of all, it is easy to install. The most striking feature of it is that it is
easy to learn. PHP is used by millions of people and developers around the world. There are thousands of websites on
the internet which are written using PHP. One primary example is Yahoo! Bookmarks. I will show you how to build
your own PHP website in the simplest way I could find. You will also learn the fundamentals of PHP and write your
own PHP code.

1.4 What we need in order to build PHP driven sites?


You need PHP Hosting. You can register a domain with a php and mysql host on the web anywhere. There
are tons of web hosting companies providing free domain names or a paid one.
You can easily install PHP and MySQL on your home computer easily (see PHP installation page). This will allow you to
write and test code on your computer and later deploy it to your PHP web hosting account.

1.5 Do you want to know if PHP is easy to learn?


It is very easy to learn especially when you take it a step at a time. Complicated things you may want to do
on your website are made easier with the usage of PHP and it will allow you to do almost anything you can imagine.
Implementing simple forms or logic on your site is very easy. Techniques of learning PHP are best shown with
examples.
If you have the will and the determination, then nothing is hard. Just follow the tutorials on my page. I will walk to
you through step by step; provide you with working examples, code and tutorials to help you learn PHP. My goal is to
make the learning process fun and easy for you. If you have any question or need help, you can email me
(sashakil_4u@rediff.com).

1.6 What can PHP personally do for you?


It can greatly increase the functionality of your websites. It will allow you to write scripts which will allow
your visitors to interact with you through your website. If you are the owner of a small business website, you can use
PHP to let your users send feed back to you in relation to your ad services, products, or even create forms which will
allow your website visitors to send you emails. Learn PHP, you will find out what you have been missing in your web
design and development.

1.7 Installing PHP on Windows


Installing PHP is easy. Abyss Web Server is a good Local Webhost. To download Abyss Web Server, browse
http://www.aprelium.com/downloads. Follow the provided instructions and choose the correct version of the
software suitable to your computer and to the operating system you are using.
Visit http://www.aprelium.com/abyssws/scripting.html for configuring your PHP host. Once configured, you are now
ready to test your php experiences by using your local host.
[2]

2. PHP Syntax
Welcome! In this section we're going to learn how PHP and HTML works together. We are also going to build
our first PHP web page. Exciting! Are you ready?

2.1 PHP Tags


PHP is a web scripting language which means it was designed to work with HTML. You can easily embed PHP
code into your HTMl code. Hmmm! Nice but how do we do that? Simple! When writing php code, you enclose your
PHP code in special php tags. This tells the browser that we're working with PHP. See below.
<?php
//your php code goes here
?>

2.2 PHP and HTML


Now let see how we blend PHP and HTML together.
<html>
<title>my php page</title>
<body>
<?php
echo "hello there!";
?>
</body>
</html>
Echo is a special statement in php for outputting data to the browser. This statement is more often used
when we need to print something to the browser. You will learn how to use echo in as we go along.
[Note: Note that, at the end of each PHP statement we need to put a semicolon, i.e. ";" as you see in the
above code. Otherwise PHP will report syntax error.]
Pretty neat, eh? I remember when I first wrote my php code, I was just so amazed.
So, let do that. Let’s write our first PHP page.

2.3 My First PHP Page


1. Open up notepad.
2. Copy-paste the above PHP and HTML code in notepad.
3. Now, lets save the file in your root folder, i.e. C:/ Abyss Web Server / htdocs/
[Remember, we need PHP to run PHP pages on our computer. To install PHP, please go to the PHP installation page.]
4. Name the file my_php_page.php and save it in your htdocs folder.
[All PHP files must be saved with extension *.php. This is important because we need to tell the browser that we are
working with PHP.]
5. Now, go to http://localhost/my_php_page.php in your web browser.
You should see "hello there!" printed out on the browser. Pretty simple, eh?
There you have your first web page in PHP. Now, let’s play around with the code. Let’s do some more cool stuff.

2.4 Doing Cool Stuff with PHP and HTML


Echo statement is powerful in a sense that you can put HTML code in it and it will render the text as if it was
HTML in your browser. Try it!
Example - Make Text Bold
Replace the PHP line in your code to the following code. Save the file and now refresh your page.
<?php
echo "<b>hello there!</b>";
?>>
You should see hello there! in bold letters in your browser.
Example - Make Text Green
Replace the PHP line in your code to the following code. Save the file and now refresh your page.
<?php
echo "<font color='green'>hello there!</font>";
?>>
You should see “hello there!” in green color in your browser.
[3]

Example - What's today's date?


Let’s print out today's date using the php date function. Don't worry we will see more examples of the date
function in later tutorials. We will learn some useful techniques for printing date in different formats. For now, let's
try the following code.
<?php
echo "today is ".date('Y-m-d');
?>
Try it! Replace previous echo line with this line. You should see today's date, "today is 2010-02-27", printed
out on your browser.
So, in this section we saw how we can add PHP into our HTML code. This should give you a brief glimpse into
how PHP works and what we can do with it. You're now ready to move on to some advance PHP stuff! What are we
waiting for, let’s go!

3. PHP Variables
Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values
in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a
variable. When ever we need to use these values, we simply call that variable instead writing out those values over
and over again in our code. Here is an example.
<?php
$str="I love PHP"; //here is one variable with a string value
echo $str; // here we print the $str value onto the browser

$num = 100; //another variable with a integer value


echo $num; // here we echo the $num variable to print its value

echo $str; //here we reuse the $str variable to print its value again in our
code
echo $num; //here we reuse the $num variable to print its value again in our
code
?>
The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save
the file as php and run it on your browser.
Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign,
then write the variable name and finally assign a value to it. Here is an example below.
$variable_name = value;

3.1 Few Naming Rules


There are few things we need to note when working with PHP variables.
• A variable name should only start with underscore "_" or a letter.
• A variable can only contain letters, numbers or underscore. In another words, you can't use other funky
characters like <^# in your variables names.

3.2 Declaring a PHP Variable


Let's consider we want to store values using variables in PHP. Here's how we do it.
• First, think of a logical name for a variable. For example, if we want to store the text of your company logo in
a variable, the logical name for that variable would be something like $logo_text. Remember, you can name
your variables whatever you like. But you must choose logical names so it is easier to remember what they
are.
• Assign that variable a value.
• Remember to put the $ sign in front of the variable name.
Let's look at some example...
Example - PHP variable with a string value
<?php
$logo_text = "PHP-Learn-It! Learn PHP by examples";
echo $logo_text;
?>
Example - PHP variable with an integer value
<?php
$number = 100;
[4]

echo $number;
?>
Example - PHP variable with a float or decimal value
<?php
$decimal_number = 100.01;
printf("%.2f", $decimal_number);
?>
In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print
its value onto the page.

3.3 Some key points to remember when declaring variables in PHP


• Remember to always put $ sign in front of variable names. That tells PHP that we're working with a variable.
• In PHP a variable name must start with a letter or an underscore followed by combination of letters, number
or underscores.
• PHP variables are case sensitive, that means they could be either lower case or upper case or combination of
both.
• You don't have to worry about declaring the type of the variable. For example strings and integers are
declared the same way.
• It's good practice to initialize a variable i.e. assign it a value. Uninitialized variables in PHP have a value of
either false, empty string or empty array.

4. PHP Variables Made Clear with Examples


4.1 How to define a float variable in PHP?
You define a float or a decimal variable just the way you define any variable in PHP.
<?php
$float_var = 3.5322322;
printf(“%.1f”, $float_var);
?>

4.2 How to declare an integer variable in PHP?


PHP doesn’t care about primitive types. You can simply declare an integer variable the way you declare string
variables.
<?php
$integer_var = 3;
echo $integer_var;
?>

4.3 How to concatenate variables in PHP?


You can use the ‘.’ operater in PHP to concatenate two variables.
<?php
$integer_var = 3;
$str_var = “apples”;
echo $integer_var.” “.$str_var;
?>

4.4 What is Variable Scope in PHP?


In PHP you can’t access a variable which is defined outside its scope. How is scope determined? In a PHP
script, variables defined outside functions can’t be accessed inside the functions.
<?php
$integer_var = 3;
function print_var(){
// this won’t print 3 since $integer_var is not in the scope of this
function
echo $integer_var;
}
print_var();
?>
[5]

4.5 How to define a global variable in PHP?


If you want variables defined out side the function to be accessed inside the function scope then you have to
make them global inside the function. You can use the global term.
<?php
$integer_var = 3;
function print_var(){
global $integer_var;
echo $integer_var; // echos 3 on the screen
}
print_var();
?>

4.6 How to cast variables in PHP?


Casting in PHP works the same as in Java or C++. You write the cast type in brackets before the variable.
<?php
$integer_var = 3;
function print_var(){
$integer_var = 3;
echo (float)$integer_var; // now casted to float
}
print_var();
?>
Allow cast types:
(5oolean)
(int)
(string)
(array)
(object)

4.7 How to concatenate variables using .=?


You can use the ‘.’ operator in PHP to concatenate two variables.
<?php
$str_var = “apples”;
$str_var .= “ and oranges”;
echo $str_var;
?>
The example above outputs “apples and oranges”.

4.8 PHP Variable type juggling in PHP


PHP doesn’t require variables be declared using primitive types. Therefore, juggling between two types
doesn’t require use of any special function. We can simply do things like…
<?php
$var = “0”; //string var
$var += 2.5; //var is now float
$var += 2; //var is now integer
$var .= “ is the total”; //var is now string
echo $var;
?>
The above code outputs “4.5 is the total”.

5. PHP Strings Operators


Welcome! In programming, a string is a sequence of letters, symbols, characters and arithmetic values or
combination of all tied together in single or double quotes.

5.1 Strings in PHP


Example - PHP String
<?php
$str = "I Love PHP";
echo $str
[6]

?>
In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output
its value.

5.2 Concatenating Strings in PHP


Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to
concatenate two or more strings together to form a single string.
Example 1 - Concatenating PHP Strings
<?php
$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>
In the above example we join $str1, empty string and $str2 to form a single string. The above code will
output "I Love PHP. PHP is fun to learn."
Example 2 - Concatenating PHP Strings
Another way you to concatenate strings in PHP.
<?php
$str1 = "I Love PHP.";
$str2 = $str1." PHP is fun to learn.";
echo $str2;
?>
In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and
echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

5.3 PHP Strings in Single and Double Quotes


5.3a Strings in Double Quotes
As we saw in our 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 a single quotes
with in double quotes.
[Special characters are escaped using backslash. Sometimes we need escape special characters in our strings.
We will learn about in the following section.]
Example - String in Double Quotes
<?php
$str = "It's a nice day today."
echo $str;
?>
Notice the apostrophe. It's a special character which we didn't need to escape in double quotes.
5.3b Strings in Single Quotes
Example - String in Single Quotes
<?php
$str = 'This is a PHP string examples in single quotes';
echo $str;
?>

5.4 Single Quotes vs. Double Quotes


Then, looking at single quote strings and double strings you may think there is any difference. However,
there are reasons for using single quotes and doubles in a string.
Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes
with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use
single quotes when wrapping an HTML code in PHP. Here's an example.
Example - Single Quotes used for wrapping HTML Code
<?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
‘\n’ and ‘\r’. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable
to use double quotes. For example…
Example - Variable Wrapped in Double Quote String
[7]

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

5.5 Escaping Special Characters


As mentioned above we can escape characters in a string using backslash. An example would be using quotes
inside quotes in a string. Let's have a look.
Example - Escaping quotes with in quotes
<?php
$str = "\"This is a PHP string examples in double quotes\"";
echo $str;
?>
Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP
string examples in double quotes" in double quotes.
And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.
<?php
$str = 'It\'s a nice day today.';
echo $str;
?>
In the above example we escaped the apostrophe using a backslash like this \'.

5.6 Useful PHP String Functions


Here we will list some of the commonly used PHP string functions.
Example - strlen() Function
This function returns the number of characters in a string. It takes a string as an argument.
<?php
$str = "Hello!";
echo strlen($str);
?>
The above will output 6.
Example - 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.
<?php
$str = "Hello! How are you today?";
echo str_replace("Hello", "Hi", $str);
?>
In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi!
How are you today?"
Example - strtoupper() Function
This function converts all lower case letters to upper.
<?php
$str = "hello!";
echo strtoupper($str);
?>
The above example will output "HELLO!"
Example - ucfirst() Function
This function changes the first letter in the string to upper case.
<?php
$str = "hello!";
echo ucfirst($str);
?>
The above example will output "Hello!"
Example - trim() Function
This function removes whitespace from the beginning and from the end of the string.
<?php
$str = " hello! ";
echo trim($str);
[8]

?>
The above example will output "hello!"

6. PHP Operators
Welcome! In this section we’re going to cover different kinds of operators we use in programming. These
operators are common to ever language. So, in PHP they are no longer different. We will go through each type of
operators with examples on how they are done in PHP.

6.1 Arithmetic Operators


In programming, we often perform arithmetic operations to calculate values. Below is the list of these
operators with examples.
Operator Name Example Output
+ Addition <?php 10
$num = 5+5;
echo $num
?>
- Subtraction <?php 0
$num = 5-5;
echo $num
?>
* Multiplication <?php 25
$num = 5*5;
echo $num
?>
/ Division <?php 1
$num = 5/5;
echo $num
?>

6.2 Comparison Operators


Comparison Operators prove very useful when checking the status of two variables or values. For example, if
you want to check if one is equal to the other, we would use = operator. Comparison operators are used in logic
conditional statements (check PHP If...else section) to evaluate if the condition is true or false.
Operator Name Example Output
> is greater than 6 > 5 First example returns true.

5 > 6 Second example returns false.


< is less than 6 < 5 First example returns false.

5 < 6 Second example returns true.


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

6.3 Logic Operators


Logic operators can be used to combine two or more comparison statements combined into one statement
to determine its status. For example, we can check to see if value A greater than value B and value B greater then
value C. Let's check out some examples.
Operator Name Example Output
&& and (6 > 5 && 1 < 7) returns true
|| or (2 > 5 || 1 < 7) returns true
If you're not familiar with the logic operations and their usage, please refer to the table below for reference.
The table shows what you would get back when performing logic operation on two values p and q where T = True and
F = False.
p q p and q p or q
T T T T
T F F T
F T F T
F F F F
[9]

7. PHP If Else Statement


Welcome! In this section we are going to learn how to write conditional statements in PHP using "if, else if
and else" clause.
Often in programming while writing code to solve problems, we require to perform certain actions based on
certain conditions. For example, in our application, we might want to display different messages to the users on our
page based on what day of the week it is. In order to handle this, we write what we call conditional statements where
each action is performed based on a condition and when that condition is true. Here's what I mean...
if (condition)
perform action 1
else
perform action 2
The above pseudo-code translates... if the first condition is true, then perform action 1, otherwise perform
action 2.

7.1 The If...Else Statement in PHP


Let's examine some code to get an idea how conditional statements are done in PHP. In the following
example, we evaluate what day of the week it is today. Based on that we display an appropriate message to the user.
Example - If..Else Statement in PHP (without curly brackets)
<html>
<body>
<?php
$day = date("l"); //Give what day of the week it is. Returns Sunday
through Saturday.
if ($day == "Saturday")
echo "It's party time :)";
else
echo "Ahhh! I hate work days.";
?>
</body>
</html>
In the above example, we first determine what day of the week it is, and then write a small if statement
(conditional statement) to see if today is Saturday. If it is true, then the code will output "It's party time :)", else (if it is
not Saturday), the second condition will come true and the code will output "Ahhh! I hate work days.".

7.2 PHP If Esle Using Curly Brackets


In the above example, we wrote one line of code in-between the if and else statements. What if we want to
write more then one line of code in there? Well, for that we will have to remember to use the "{" curly brackets. You
must enclose the action part of the code in curly brackets. Failing to do that will cause an error. Let's tweak our first
example to see how this is done.
Example - IF Else Using Curly Brackets
<html>
<body>
<?php
$day = date("l"); //Give what day of the week it is.
if ($day == "Saturday")
{
echo "It's party time :)";
echo " Where are you going this evening?";
}
else
{
echo "Ahhh! I hate work days.";
echo " I want weekend to come :)";
}
?>
</body>
</html>
[10]

In the above example, we use the curly brackets to enclose the action part of the conditional statements
when we have more than one line in there.

7.3 The Elseif Statement in PHP


In the above section, you saw how to write two conditional statements using "If and Else". What if we want to have
more than two conditional statements? We can have as many conditional statements as we want in your code. To do
that, we have to use "elseif" between our "if" and "else" statements. Let's say in our above example we also want to
print a message for Fridays to our users saying "Have a nice weekend!". We would use the elseif clause to do that.
Let's see how that is done.
Example - The Elseif Statement
<html>
<body>
<?php
$day = date("l"); //Give what day of the week it is.
if ($day == "Saturday")
{
echo "It's party time :)";
echo " Where are you going this evening?";
}
elseif ($day == "Friday")
{
echo "Have a nice day!";
}
else
{
echo "Ahhh! I hate work days.";
echo " I want weekend to come :)";
}
?>
</body>
</html>
Now the users will see "Have a nice day!" if the today is Friday. Pretty handy eh!
So, as you saw, if..else conditional statements can help us write some logic and help us take decisions in our
code. You will find yourself writing conditional statements a lot in your code. So, make sure you grasp this topic. You
will see the use of conditional statements a lot in the rest of the tutorials.

8. PHP Switch Statement


Welcome! Switch statements are just like ‘if..else’ conditional statements where a block of code is executed
if the condition is true. Let’s look at the syntax of a switch statement...

8.1 Switch Statement Syntax


switch (expression)
{
case case_1:
//execute first block of code
break;
case case_2:
//execute second block of code
break;
case case_3:
//execute third block of code
break;
default:
//execute this block of code if expression doesn't match any
case
}
[11]

8.2 PHP Switch Statement


Switch statement should be used in the code when you want to evaluate different cases of a given scenario.
The switch statement takes a single variable as input and then checks it against all cases we have in our switch
statement.
Let's imagine you own a computer retail store. Depending on the product name we want to display the price
of that product.
Now, instead writing separate if else statements for each product name, we simple use the PHP switch
statement on the product name variable to evaluate which product we want to the display the price for. Let's have
look at the example.
Example - PHP Switch Statement
<html>
<body>
<?php
$product_name = "Processors"; //set product name
switch ($product_name)
{
case "Video Cards":
echo "Video cards range from $50 to $500";
break;
case "Monitors":
echo "LCD monitors range from $200 to $400";
break;
case "Processors":
echo "Intel processors range from $100 to $1000";
break;
default:
echo "Sorry, we don't carry $product_name in our catalog";
break;
}
?>
</body>
</html>
The above switch statements evaluate the product name and display the price range for that product. Since,
we set the $product_name to "Processor", the above code outputs "Intel processors range from $100 to $1000".

8.3 PHP Switch Statement: The default case


What if someone asks for a product we don't carry? In that case, the default statement in switch code will be
executed. In the example below we set the product name to "Briefcase".
Example- The Default Case in PHP Switch Statement
<html>
<body>
<?php
$product_name = " Briefcase"; //set product name
switch ($product_name)
{
case "Video Cards":
echo "Video cards range from $50 to $500";
break;
case "Monitors":
echo "LCD monitors range from $200 to $400";
break;
case "Processors":
echo "Intel processors range from $100 to $1000";
break;
default:
echo "Sorry, we don't carry $product_name in our catalogue";
break;
}
[12]

?>
</body>
</html>
The code will execute the default code block since we don't carry ‘Briefcase’ and it is not part of our switch
statement cases. The code will output "Sorry, we don't carry Briefcase in our catalog".
[Tip: It is always good to include the default case in your switch statements. It will help you debug your code
better during testing. In case, none of your switch cases match in your switch statement during code execution, the
default case will be executed.]

8.4 PHP Switch Statement: The Break Statement


The break statement in PHP switch code prevents the code from executing other cases in the switch
statement when a case is matched to a switch statement, the break statement basically stops the code execution. If
the break statement is not there, then each case is executed. Consider the following example with two same product
cases.
Example- The Break Statement in PHP Switch Statement
<html>
<body>
<?php
$product_name = "Processors"; //set product name
switch ($product_name){
case "Video Cards":
echo "Video cards range from $50 to $500";
case "Monitors":
echo "LCD monitors range from $200 to $400";
case "Processors":
echo "Intel processors range from $100 to $1000";
case "Processors":
echo "AMD processors range from $100 to $1000";
}
?>
</body>
</html>
As we can see in the above example, we don't have the break statement after each switch case and we have
two cases for the product "Processors". So, the above code will evaluate both cases for "Processors".
The code evaluates the first case and prints "Intel processors range from $100 to $1000" and then it goes to
the next case and prints "AMD processors range from $100 to $1000".
[Tip: If you're a new to switch statements, it is good to use the break statement in your switch cases to
prevent any confusion.]

9. PHP Arrays
Welcome! In this section we cover what arrays are, what they are used for and how to work with arrays in
PHP. What is PHP Array?
An array is a mean to store collection of values in a single variable. Imagine, if you own a shop and you want
to store the names of your employees. Now, instead of creating a separate variable to store each employee's name,
you can use an array to store the names of all your employees in a single variable. This is how you would do it.
Example - PHP Array
$employee_names[0] = "Dana";
$employee_names[1] = "Matt";
$employee_names[2] = "Susan";
Each value in the array above is stored as an element and each element is associated to an id or a key which
you see in the square brackets.

9.1 Working with PHP Arrays


There are two types of arrays we deal with in PHP.
• Numeric Arrays
• Associative Arrays

9.2 Numeric Arrays


In a numeric array we store each element with a numeric ID key.
[13]

9.3 Creating an Numeric Array


There are two ways to create a numeric array. Let’s look at each example to see how we do that.
Example 1 - Creating a Numeric Array in PHP
<?php
$employee_names[0] = "Dana";
$employee_names[1] = "Matt";
$employee_names[2] = "Susan";
echo "The first employee's name is ".$employee_names[0];
echo "<br>";
echo "The second employee's name is ".$employee_names[1];
echo "<br>";
echo "The third employee's name is ".$employee_names[2];
?>
[See, echo "<br>" inserts a line break after each sentence in our example above.]
The above code create a numeric array employee_names and outputs...
"The first employee's name is Dana".
"The second employee's name is Matt".
"The third employee's name is Susan".
Example 2 - Creating a Numeric Array in PHP
The example below is an another way of creating a numeric array. Let's have a look.
<?php
$employee_names = array("Dana", "Matt", "Susan");
echo "The third employee's name is ".$employee_names[2];
?>
The above code creates a numeric array employee_names and outputs "The third employee's name is
Susan".

9.4 Associative Arrays


When we want to store elements in array with some meaningful association other than numbers, we use
associative array. For example, let 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.

9.5 Creating an Associative Array


There are two ways to create a associative array. Let’s look at each example to see how we do that.
Example 1 - Creating a PHP Associative Array
<?php
$employee_title["Dana"] = "Owner";
$employee_title["Matt"] = "Manager";
$employee_title["Susan"] = "Cashier";
echo "Matt is the ".$employee_title["Matt"];
?>
Example 2 - Creating a PHP Associative Array
<?php
$employee_names = array("Dana" => "Owner", "Matt" => "Manager", "Susan" =>
"Cashier");
echo "Matt is the ".$employee_title["Matt"];
?>
In both examples above, we create an associative array $employee_title and output "Matt is the Manger".

9.6 Multidimensional Arrays


Let’s extend our idea of associating a single key to an element. What if we want to associate multiple keys to
an element? Consider the Employees Table/Matrix below.
Employees Table/Matrix
name title salary
employee 1 Dana Owner $60,000
employee 2 Matt Manager $40,000
employee 3 Susan Clerk $30,000
[14]

Hmmm, that's nice but how the heck would I store employees table in an array? Simple! PHP allows us to do
that using multidimensional arrays. Let's look at the examples below to see how we would do that.

9.7 Creating Multidimensional Array in PHP


Again, there are two ways to create a multidimensional array. Let’s look at each example to see how we do
that.
Example 1 - Creating Multidimensional Array in PHP
<?php
$employees["employee 1"]["name"] = "Dana";
$employees["employee 1"]["title"] = "Owner";
$employees["employee 1"]["salary"] = "$60,000";
$employees["employee 2"]["name"] = "Matt";
$employees["employee 2"]["title"] = "Manager";
$employees["employee 2"]["salary"] = "$40,000";
$employees["employee 3"]["name"] = "Susan";
$employees["employee 3"]["title"] = "Cashier";
$employees["employee 3"]["salary"] = "$30,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 an multidimensional array name employees and outputs "Matt is the Manager and
he earns $40,000 a year.".
Example 2 - Creating Multidimensional Array in PHP
<?php
$employees = array
(

"employee 1" => array


(
"name" => "Dana",
"title" => "Owner",
"salary" => "$60,000",
),

"employee 2" => array


(
"name" => "Matt",
"title" => "Manager",
"salary" => "$40,000",
),

"employee 3" => array


(
"name" => "Susan",
"title" => "Cashier",
"salary" => "$30,000",
)
);

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


" is the ".$employees["employee 1"]["title"].
" and they earn ".$employees["employee 1"]["salary"].
" a year.";
?>
The above code creates a multidimensional array name employees and outputs "Dana is the Owner and they
earn $60,000 a year."

9.8 Printing PHP Arrays?


To print the results of an array you can use the PHP function print_r() to print an array. See example below.
<?php
[15]

$employee_title["Dana"] = "Owner";
$employee_title["Matt"] = "Manager";
$employee_title["Susan"] = "Cashier";

echo "<pre>";
print_r($employee_title);
echo "</pre>";
?>
The array result will print out as follow...
Array
(
[Dana] => Owner
[Matt] => Manager
[Susan] => Cashier
)
[Note: Always remember to use <pre></pre> tags while printing an array as shown above otherwise the
result is not very reader friendly.]

Summary
So, in this section we covered an important lesson on arrays. You will find yourself using arrays a lot when
programming in PHP because its the most easy and useful way of storing values. The usefulness of arrays will become
more apparent in the next lesson, PHP Loops.

10. Loops in PHP: foreach() Loop


Welcome! In programming, we often want to repeat a block of code to solve a problem. Instead of writing
that block of code over and over again, we can use loops to iterate through the code for however number of times we
want.

10.1 Types of Loops in PHP


There are three types of loops often used while programming in PHP.
• foreach loop
• for loop
• while loop
Let's go through each type with examples to a have better understanding on how to used them in PHP.

10.2 Foreach Loop


Foreach loop is most often used to print elements in a array.

10.3 Foreach Loop Syntax


foreach (array as $value)
{
//code block to be run inside loop
}
On every iteration of a foreach loop, the value of the current array is assigned to $value.

10.4 Using Foreach Loop with Array


Let's imagine we want a drop down box list of our favorite browsers. We can use an array to store the names
of the browsers and use PHP foreach loop in conjunction with HTML to make the drop down box. Let have a look at
the code example to see how that is done.
Example 1 - Using foreach to print values in an array
<?php
$browsers = array ("Firefox", "Internet Explorer", "Opera");
echo "<select>";
foreach($browsers as $browser)
{
echo "<option name='$browser'>$browser</option>";
}
echo "</select>";
?>
[16]

Firefox
The above code will output our drop down box.

10.5 Using Foreach Loop with Key - Value Pair Array


In last section, PHP Arrays, we learned multidimensional arrays. We can use foreach loop to print the keys and the
values from a multidimensional array. What am I talking about?
Let say we have an multidimensional array of articles. In our array the article title is the key and the article body is the
value. We will use foreach loop to print the articles onto our web page. Let see how that is done.
Example 1 - Using foreach to print key - values pairs in an array
<?php
$articles = array
(
"PHP Variables" => "A variable is a mean to store values
such as strings or integers so we can easily
reuse those values in our code...",

"PHP Strings" => "A string is a sequence of letters, symbols,


characters and arithmetic values...",

"PHP Lopps" => "In programming, we often repeat an action or a


piece of code a number of times using loops
to solve a problem..."
);
echo "<table border='1'>";
foreach ($articles as $article_title => $article_body)
{
echo "<tr>";
echo "<td>";
echo $article_title;
echo "</td>";

echo "<td>";
echo $article_body;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
So, in the above example we define an array of articles with key being the article title and value being the
article body. Next we use foreach loop to print the array keys and values in a table.
The above example will print our articles in a table as below. Pretty neat eh? Loops can save a lot of time from doing
repetitive things.
[The operator "=>" represents the relationship between the key and value. So, in our example above, the
$article_title is our key and $article_body is the value.]
Output:
PHP A variable is a mean to store values such as strings or integers so we can easily reuse those values in
Variables our code...
PHP Strings A string is a sequence of letters, symbols, characters and arithmetic values...
PHP Loops In programming, we often repeat an action or a piece of code a number of times using loops to solve
a problem...

Now let's look at the next type of looping technique we use in php, the for loop.

11. Loops in PHP: for() Loop


Welcome! In this section we’re going to cover the use of for loops in PHP.

11.1 For Loops


A for loop is used when we want to execute a block of code for certain number of times. For example,
printing a value 5 times.
[17]

11.2 For Loop Syntax


for(initialize counter; condition until counter is reached; increment counter)
{
//execute block of code
}
For loop has three statements.
• In the first statement, we initialize a counter variable to a number value.
• In the second statement, we set a condition (a max/min number value) until the counter is reached.
• In the third statement, we set a value by how much we want the counter variable to incremented by.
Lets look at an example to see how to create a for loop in PHP.

11.3 PHP For Loop


Example - Print number through 0 to 5 with PHP For Loop
<?php
for($i=0; $i<=5; $i=$i+1)
{
echo $i." ";
}
?>
In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the
condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we
set $i to increment by 1.
The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.
[Note: The third increment statement can be set to increment by any number. In our above example, we can
set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.]
Example - Print number through 5 to 0 with PHP For Loop
What if we want to go backwards, i.e. print number though 0 to 5 in reverse order? We simple initialize the
counter variable $i to 5, set its condition to 0 and decrement $i by 1.
<?php
for($i=5; $i>=0; $i=$i-1)
{
echo $i." ";
}
?>
The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.
Example - Print table with alternate colors using PHP For Loop
Let's have a look an interesting example of php for loop. You often seen tables cell with alternate colors on
different websites. So, let say we want to print the numbers in a table with alternate colors. This is how we would do
it.
0
1
2
3
4
5
<?php
echo "<table width='100' align='center'>";
for($i=0; $i<=5; $i=$i+1)
{
if($i % 2 == 0)
{
echo "<tr>";
echo "<td style='background-color:red'>";
echo $i;
echo "</td>";
echo "</tr>";
}
else
{
[18]

echo "<tr>";
echo "<td style='background-color:green'>";
echo $i;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
?>
The above code sets different background color to the table cells depending on the value of $i. If $i is
divisible by 2, which means if it is even then display color green, otherwise display color red.
Now that we are familiar with PHP for loop. Now, let's take a look at the last type of loop, the while loop in PHP.

12. Loops in PHP: while() Loop


Welcome! In this section we going to cover the use of while loops in PHP.

12.1 While Loops


Just like the for loop, while loop is used to execute a block of code for certain number of times until the
condition in the while evaluate to true.

12.2 While Loop Syntax


while(condition)
{
//execute block of code
}
[Note: The condition statement must evaluate to true for the loop to exit otherwise the loop will run
forever.]

12.3 PHP While Loop


Example - Print number through 1 to 5 with PHP While Loop
Example below prints integers through 1 to 5
<?php
$i = 1;
while ($i <= 5 )
{
echo $i . "<br>";

$i = $i + 1;
}
?>
In the above example, you see that the loop is run until the value of $i is less than or equal to 5 according to
the condition in the loop. The $i = $i + 1; statement increments the value of $i by 1 on each iteration of our while
loop.
Example - Print decimal number through 1.0 to 5.0 with PHP While Loop
Here is another example with decimal numbers.
Example below prints decimal numbers through 1.0 to 5.0
<?php
$i = 1.0;
while ($i <= 5.0 )
{
printf("%.1f<br>", $i);
$i = $i + 1.0;
}
?>

12.4 Breaking out of a PHP Loop


We can use the break; statement to stop the loop from executing.
Sometimes when we are working with loops, we want to break the loop when a certain condition is true.
For example, we might want to break our loop when $i reaches 4. Let’s look at the example below.
<?php
[19]

$i = 1;
while ($i <= 5 )
{
if($i == 4)
break;
echo $i . "<br>";
$i = $i + 1;
}
?>
In the above example, we break the loop when $i reaches 4. The loop outputs...
1
2
3

13. PHP Functions


Welcome! In this section we are going to cover PHP functions.

13.1 What are Functions?


In technical terms, a function is a group of instructions to perform a task. In layman’s term, a function is a
block of code with a name which can be used in our code whenever we need it.
The concept might be new to you but when you look at what a function is, you will be amazed how useful
and simple it is to create a function. So, let's have a look at what a function looks like...
Function Syntax
function my_function_name(parameters)
{
//block of code
}
A typical function has three components to it
• Starts with the word function
• Has a function name followed by parentheses (). A function name can only start with a letter or a
underscore.
• The code block in the function always goes inside curly brackets.
Now, let's look a how we create functions in PHP.

13.2 A Simple PHP Function


Example - Creating and Calling a PHP Function
<html>
<body>
<?php
function my_function() //we create a function name my_function
{
echo "Hello! How are you?";
}

my_function(); //we call our function like this when we want to use it
?>
</body>
</html>
In the above code, we create our own function name my_function() and we call that function by just typing
the its name. The above code outputs "Hello! How are you?".

13.3 PHP Function with Parameters


A function can be used to pass arguments (values or information) into it through parameters. This is useful
when we want to add more functionality to our functions. For example, we can modify the above function to pass a
person's name and a message into it and display that information.
[Note: Parameters appear within the parentheses "()". They are like normal PHP variable.]
Example - PHP Functions with Parameters
<html>
<body>
[20]

<?php
//we create a function named my_function
function my_function($first_name, $last_name, $message)
{
echo "$first_name $last_name once said " . $message;
}

//we call our function like this when we want to use it


my_function("Duke", "Nukem", '"It\'s time to kick some ass and chew bubble
gum."');

?>
</body>
</html>
In the above example we created a function with three parameters, $first_name, $last_name and $message.
We used these parameters to send our custom arguments (values) to our function. The above example outputs...
Duke Nukem once said "It's time to kick some ass and chew bubble gum.".
[Note: In our function we can make as many parameters as we want. Parameters appear within the
parentheses "()". They are like normal PHP variable.]
Hopefully, now you're are beginning to see the use of functions and realizing how useful they are.

13.4 PHP Functions with Return value


We can have functions to return a value. So, instead of echoing or printing value inside the function, we can
have the function return that value. That value can be anything. It can be a string, an integer, a float value, an array or
an object. We use the term return to return a value in a function.
[Note: Functions can only return value once. That means you can only the use the return statement once in
your function.]
Let's modify our function return a value.
Example - PHP Function returning a String value
<html>
<body>
<?php

//we create a function named my_function


function my_function($name) {
return "hello there $name!";
}

//we call our function like this when we want to use it


echo my_function("Matt");

?>
</body>
</html>
The above function returns our string value instead echoing it inside. We call the function and echo its value
outside. The above code outputs "hello there Matt!"
Pretty neat eh! Let's look at more examples.
Example - PHP Function returning a Integer value
Let's create a function to return an integer value.
<html>
<body>
<?php
function my_function($price, $tax) //we create a function named my_function
{
$total_price = $price + $tax;
return $total_price;
}
[21]

//we call our function like this when we want to use it


echo "The total price after tax: \$" . my_function(50, 5);

?>
</body>
</html>
In the above function we calculate the total price and return it. The code outputs The total price after tax:
$55.

Summary
Hopefully now you can see how we use functions in our code. We can use functions to organize our code
into little meaningful chunks and use them as we need them in our code.

14. PHP Comments


Welcome! Comments are used to describe your code. When you write a block of code to accomplish
something, it is good practice to write what you have done in that code. More precisely explain what the code does
using comments.
Now let's see how we write comments in our code.

14.1 Types of Comments in PHP


There are two ways to write comments in your PHP code.
• Single Line Comments
• Multiple Line Comments

14.2 Single Line comments in PHP


Single line comments are written using two forward slashes, "//". Any line in your PHP code with // in front
will be ignored and treated as comments. Let’s take a look at an example.
Example - Single Line Comments
<html>
<title>my php page</title>
<body>
<?php
// print hello there on the screen
echo "hello there!";
//echo "this php line will be ignored by the interpreter";
?>
</body>
</html>
In the above example we described the echo line code using a single line comment "// print hello there on
the screen".
Also notice that we put // in front of the echo on the last line. Even thou that line is a valid PHP code but it is
treated as a comment and is ignored by the PHP interpreter.

14.3 Multiple Line Comments in PHP


Multiple line PHP comment begins with "/*" and ends with "*/". So, anything inside /* */ will be treated as
comments by the PHP interpreter.
Multiple line comments are normally used when you have to explain a rather long block of code instead of
one line code as we saw above with the echo statement. For example, commenting what a function does would be
done using /* */. Let's have a look at an example to see what i mean.
Example - Multiple Line Comments
<html>
<title>my php page</title>
<body>
<?php

/*
* print_name: print message on the screen
* @param: $name - name to be used in the message
*/
[22]

function print_name($name)
{
// print hello there on the screen
echo "hello $name!";
}
?>
</body>
</html>

14.4 Why write comments in your code?


Comments are an integral part of your code. Most of the times you will be writing lots of code and things will
get complicated. Without comments in your code, you could get lost as to what your code does when you come back
to it later. Comments will help you remember what you did and what your code does.
It also helps to write comments when you are working in a team. Other programmers can easily tell what
your code does by reading your comments. They don't have to bother to read your code line by line to figure out
what it does. This can be really painful for the other developers.

14.5 Tips on writing comments


When writing comments describe what the code does instead describing how the code works. Newbie’s and
students usually make this mistake. Use single line comments when describing a single line of code and use multiple
line comments when describing a block of code.

15. PHP Email


Welcome! In this section we’re going to cover how to use the mail function in PHP to send emails.
PHP has a built in function mail for sending emails. Using this function we can send plain text emails or HTML emails.

15.1 PHP Mail Function


mail($to, $subject, $message, $headers);
As you can see above, the mail function has four parameters.
to - the recipients email address
subject - the subject of the email.
message - the email message to be sent.
headers - the header contains information such as the format of the email (plain text or HTML), senders name and
email, reply to address, CC and BCC.

15.2 Sending Plain Text Email in PHP


The following code will send out a plain text email using the PHP built in mail function.
PHP: Send plain text email
<?php
function send_email($from, $to, $cc, $bcc, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "CC: ".$cc."\r\n";
$headers .= "BCC: ".$to."\r\n";

if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email could not be sent";
}
}

$subject = "Hello!";
$message = "Hello! How are you today?";
send_email("youraddress@domain.com", "recpeient@domain.com",
"someone@domain.com", "hidden_email@domain.com",
$subject ,
[23]

$message);
?>
In our send_email function we set the appropriate headers. Reply-To and Return-Path points to the email
you want the recipient to reply to. Some server requires the use of Return-Path, so it's good to leave it in there.
Next we call the send_email function which sends out the email.

15.3 Sending HTML Email in PHP


The following function will send out an HTML formatted email using the PHP built in mail function.
PHP: Send HTML email
<?php
function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "Content-type: text/html\r\n";

if (mail($to,$subject,$message,$headers) ) {
echo "email sent";
} else {
echo "email couldn't be sent";
}
}

$subject = "Helloooo!";
$message .= "<html><body>";
$message .= "<b>Hey! How are you today?</b>";
$message .= "<br>Regards";
$message .= "</body></html>";
send_email("youraddress@domain.com", "recpeient@domain.com",
$subject ,
$message);
?>
In our send_email function we set the content type headers to text/html. It is important to do so because it
tells the email server that the email contains html code and to format and display the email correctly when it is
opened.

16. PHP Date Function


16.1 PHP Dates Formats
Displaying dates in different formats.
<?php
echo date("Y-m-d");
echo date("Y/m/d");
echo date("M d, Y");
echo date("F d, Y");
echo date("D M d, Y");
echo date("l F d, Y");
echo date("l F d, Y, h:i:s");
echo date("l F d, Y, h:i A");
?>
Output
2010-02-27
2010/02/27
Feb 27, 2010
February 27, 2010
Sat Feb 27, 2010
Saturday February 27, 2010
[24]

Saturday February 27, 2010, 10:16:35


Saturday February 27, 2010, 10:16 PM

16.2 PHP Date Function Syntax


date(format, timestamp)
As seen above, the php date function take two arguments.
1. format - Always required. Specify the format to display the in.
2. timestamp - Optional. Specify UNIX time stamp. If not passed, the current timestamp is used.

16.3 PHP Date Function Parameters


format - The first parameter, format, in the date function specifies how to display the date/time. It uses different
letters to represent the date and time. Some of the letters used above are described here.
• d - The day of the month, i.e. 01-31
• m - Month representation in numbers, i.e. 01-12
• Y - Year in four digits
For complete list of date/time format reference, visit http://www.php.net/manual/en/function.date.php
timestamp - The second parameter, timestamp, is an optional parameter. Timestamp is the number of seconds since
January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.

16.4 PHP Date: Finding Date / Time


Using the 2nd timestamp parameter we can do things like say find exactly what date or day it was yesterday
or a week ago or what date it will be 1 month from today.
There are two ways we can do that.
• Using the PHP strtotime function.
• Using the PHP mktime function.
1. strtotime - Convert any English textual datetime description into a Unix timestamp.
2. mktime - Get Unix timestamp for a date.

16.5 PHP Date: Using strtotime to find date/time


Let's see some of the examples to find out dates using date and strtotime function.
Find Yesterday’s date
<?php
echo "yesterday was ".date("Y-m-d", strtotime("-1 days"));
?>
Output
yesterday was 2010-02-26
Find Date one week ago
<?php
echo "1 week form today was ".date("Y-m-d", strtotime("-1 weeks"));
?>
Output
1 week form today was 2010-02-20

16.6 PHP Date: Using mktime to find date/time


mktime could be used to find more specific things like find the next leap year in the calendar.
Find Leap Year
<?php
$day = "";

/*
* since leap year falls ever 4 years so loop for 4 times
*/
for($i=0; $i<4; $i++)
{
//get day timestamp for feburary 29 for this year
$day = date("d", mktime(0, 0, 0, 2, 29, date("Y")+$i));

/*
* check if day equals 29.
[25]

* If day is 29 then it must be the leap year. if day is 01, then it not
a leap year.
*/
if($day == 29)
{
$year = date("Y")+$i;
break;
}
}
echo "next leap year is in year $year";
?>
Output
next leap year is in year 2012
The mktime takes 6 arguments. The parameters are explained as below.
1. hour - The number of the hour.
2. minute - The number of the minute.
3. second - The number of seconds past the minute.
4. month - The number of the month.
5. day - The number of the day.
6. year - The number of year.

17. Cooking Cookies with PHP


17.1 What is a cookie?
A cookie is often used to store data which can be used to identify a user, for example, person's username.
Cookie is a small flat 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.

17.2 Example of cookie usage:


When you log into a website and check “remember me”, it will store your username (and other information
about you) in a cookie. Next time when you come back to the same website, it knows who you are and will log you in
automatically.
In this tutorial, we will learn how to write, read and delete cookies in PHP.

17.3 Creating a cookie


A cookie can be created using the setcookie function in PHP. Let’s explore this function.
setcookie($name, $value, $expire, $path, $domain, $secure)
• $name - name of the cookie. Example: "username"
• $value - value of the cookie. Example: "john"
• $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 domain is set to ".yourdomian.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.yourdomian.com" the cookie will be available under all www sub-domains, example
" www.yourdomian.com/news"
• $secure - true if cookie is being set over a secure "https" server, false otherwise, Default value is false.

17.4 Creating a cookie with setcookie


<?php
setcookie("username", "john", time()+3600);
?>
<html>
<body>
</body>
[26]

</html>
Cookie username is set with value john which is set to expire after one hour on users computer.
The function time() retrieves the current timestamp. Appending 3600 seconds (one hour) to the current time
to make the cookie to expire after one hour.
[Note: A cookie must be set before any HTML code as shown above.]

17.5 Creating a permanent cookie


Lets create a cookie which is set to last for 1 year.
<?php
setcookie("username", "john", time()+(60*60*24*365));
?>

17.6 Retrieving a cookie


Cookie information can retrieved using the predefined $_COOKIE array.
The following will retrieve our username cookie value
<?php
echo $_COOKIE["username"];
?>
Output
John
To print the entire $_COOKIE array, you can do the following
<?php
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
?>
Output
Array
(
[username] => john
)

17.7 Deleting a Cookie:


In order to delete cookies, you just set the cookie to expire in the past date.
Following will delete our username cookie.
<?php
setcookie("username", "john", time()-(60*60*24*365));
?>

18. PHP Sessions


Welcome! In this section we cover all important sessions in PHP.
Sessions are used to store information which can be used through-out the application for the entire time the
user is logged in or running the application. Each time a user visits your website, you can create a session for that user
to store information pertaining to that user.
Unlike other applications, in web applications, all the stored variables and objects are not globally available
throughout all pages (unless sent through POST or GET methods to the next page), so to tackle this problem, sessions
are utilized.
A usage of sessions would be for example, storing products in a shopping cart. On your favorite merchant
site, when you, the user, clicks on "add to shopping cart", the product information is then stored in a session (using
session variables) which is then available on the server for later use for the entire the time you browse the website.
[Note: Session information is temporary and is automatically deleted after the user leaves the website.]

18.1 Sessions in PHP


In PHP, information is stored in session variables. Now lets learn how we create a session in PHP.
Before you can store any information in session variables, you must first start up the session using the
session_start() function. See below.
<?php
session_start();
?>
[27]

<html>
<body>

</body>
</html>
When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the
session id using the PHP predefined constant PHPSESSID.
The code above starts a session for the user on the server, and assign a session id for that user's session.
[Note: The session_start() function must appear BEFORE the <html> tag]

18.2 Storing information in a session


To store information is a session variable, you must use the predefined session variable $_SESSION.
Now, as an example, let’s store user's name and their favorite color in a session. To do so you would do the
following.
<?php
session_start();

$_SESSION["username"] = "johny";
$_SESSION["color"] = "blue";
?>

18.3 Retrieving stored session information


Retrieving stored session information is really easy. You can access the stored session information on any
page without doing anything extra.
<?php
session_start();

echo $_SESSION["username"];
echo "<br/>";
echo $_SESSION["color"];
?>
Output
Johny
Blue

18.4 Destroying/deleting session information


Remember sessions are destroyed automatically after user leaves your website or closes the browser, but if
you wish to clear a session variable yourself, you can simple use the unset() function to clean the session variable.
<?php
session_start();
unset($_SESSION["username"]);
unset($_SESSION["color"]);
?>
To completely destroy all session variables in one go, you can use the session_destroy() function.
<?php
session_destroy();
?>

Thank You

You might also like