Day 3


PHP Introduction Day 1 Day 2 Day 3 Day 4 Day 5

Building web pages –

Using HTML Forms

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

Try out following example by putting the source code in test.php script.

<?phpif( $_POST[“name”] || $_POST[“age”] ){echo “Welcome “. $_POST[‘name’]. “<br />”;echo “You are “. $_POST[‘age’]. ” years old.”;exit();}

?>

<html>

<body>

<form action=”<?php $_PHP_SELF ?>” method=”POST”>

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

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

<input type=”submit” />

</form>

</body>

</html>

  • The PHP default variable $_PHP_SELF is used for the PHP script name and when you click “submit” button then same PHP script will be called and will produce following result:
  • The method = “POST” is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter.

Using PHP With HTML Forms

It is time to apply the knowledge you have obtained thus far and put it to real use. A very common application of PHP is to have an HTML form gather information from a website’s visitor and then use PHP to do process that information. In this lesson we will simulate a small business’s website that is implementing a very simple order form.

Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order information from our prospective customers we will have to make a page with an HTML form to gather the customer’s order.

Note: This is an oversimplified example to educate you how to use PHP to process HTML form information. This example is not intended nor advised to be used on a real business website.

Creating the HTML Form

If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson before continuing on.

We first create an HTML form that will let our customer choose what they would like to purchase. This file should be saved as “order.html”

order.html Code:

<html><body>

<h4> Stationary Order Form</h4>

<form action=”process.php” method=”post”>

<select name=”item”>

<option>Notebooks</option>

<option>Pens</option>

<option>Textbooks </option>

</select>

Quantity: <input name=”quantity” type=”text” />

<input type=”submit” />

</form>

</body></html>

Now that our “order.html” is complete, let us continue on and create the “process.php” file which will process the HTML form information.

 

PHP Form Processor

We want to get the “item” and “quantity” inputs that we have specified in our HTML form. The proper way to get this information would be to create two new variables, $item and $quantity and set them equal to the values that have been “posted”. The name of this file is “process.php”.

process.php Code:

<html><body>

<?php

$quantity = $_POST[‘quantity’];

$item = $_POST[‘item’];

 

echo “You ordered “. $quantity . ” ” . $item . “.<br />”;

echo “Thank you for ordering stationary!”;

 

?>

</body></html>

As you probably noticed, the name in $_POST[‘name‘] corresponds to the name that we specified in our HTML form.

Now try uploading the “order.html” and “process.php” files to a PHP enabled server and test them out. If someone selected the item Textbooks and specified a quantity of 2, then the following would be displayed on “process.php”:

process.php Code:

You ordered 2 Textbooks.

Thank you for ordering stationary!

PHP & HTML Form Review

A lot of things were going on in this example. Let us step through it to be sure you understand what was going on.

  1. We first created an HTML form “order.html” that had two input fields specified, “item” and “quantity”.
  2. We added two attributes to the form tag to point to “process.php” and set the method to “post”.
  3. We had “process.php” get the information that was posted by setting new variables equal to the values in the $_POST associative array.
  4. We used the PHP echo function to output the customers order

 

Using GET , POST , REQUEST

There are two ways the browser client can send information to the web server.

  • The GET Method
  • The POST Method

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2
  • The GET method produces a long string that appears in your server logs, in the browser’s Location: box.
  • The GET method is restricted to send upto 1024 characters only.
  • Never use GET method if you have password or other sensitive information to be sent to the server.
  • GET can’t be used to send binary data, like images or word documents, to the server.
  • The data sent by GET method can be accessed using QUERY_STRING environment variable.
  • The PHP provides $_GET associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "<br />";
     echo "You are ". $_GET['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="GET">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>

</html>

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

  • The POST method does not have any restriction on data size to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • The PHP provides $_POST associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>
The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Try out following example by putting the source code in test.php script.

<?php
  if( $_REQUEST["name"] || $_REQUEST["age"] )
  {
     echo "Welcome ". $_REQUEST['name']. "<br />";
     echo "You are ". $_REQUEST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>

Here $_PHP_SELF variable contains the name of self script in which it is being called.

 

Using POST & GET –

HTML Code Excerpt:

<form action="process.php" method="post">
<select name="item">
...
<input name="quantity" type="text" />

This HTML code specifies that the form data will be submitted to the “process.php” web page using the POST method. The way that PHP does this is to store all the “posted” values into an associative array called “$_POST”. Be sure to take notice the names of the form data names, as they represent the keys in the “$_POST” associative array.

Now that you know about associative arrays, the PHP code from “process.php” should make a litte more sense.

PHP Code Excerpt:

$quantity = $_POST['quantity'];

$item = $_POST[‘item’];

The form names are used as the keys in the associative array, so be sure that you never have two input items in your HTML form that have the same name. If you do, then you might see some problems arise.

PHP – GET

As we mentioned before, the alternative to the post method is get. If we were to change our HTML form to the get method, it would look like this:

HTML Code Excerpt:

<form action="process.php" method="get">
<select name="item">
...
<input name="quantity" type="text" />

The get method is different in that it passes the variables along to the “process.php” web page by appending them onto the end of the URL. The URL, after clicking submit, would have this added on to the end of it:

“?item=##&quantity=##”

The question mark “?” tells the browser that the following items are variables. Now that we changed the method of sending information on “order.html”, we must change the “process.php” code to use the “$_GET” associative array.

PHP Code Excerpt:

$quantity = $_GET['quantity'];
$item = $_GET['item'];

After changing the array name the script will function properly. Using the get method displays the variable information to your visitor, so be sure you are not sending password information or other sensitive items with the get method. You would not want your visitors seeing something they are not supposed to!

PHP Cookies – Background

Cookies have been around for quite some time on the internet. They were invented to allow webmaster’s to store information about the user and their visit on the user’s computer.

At first they were feared by the general public because it was believed they were a serious privacy risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are worse things to worry about and partly because all of the “trustworthy” websites now use cookies.

This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as explaining the various options you can set with your cookie.

Creating Your First PHP Cookie

When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):

  1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don’t forget it!
  2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
  3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

In this example we will be creating a cookie that stores the user’s last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie’s expiration date to two months in the future!

PHP Code:

<?php
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
?>

Don’t worry if you can’t follow the somewhat involved date calculations in this example. The important part is that you know how to set a cookie, by specifying the three important arguments: name, value and expiration date.

Retrieving Your Fresh Cookie

If your cookie hasn’t expired yet, let’s retrieve it from the user’s PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!

PHP Code:

<?php
if(isset($_COOKIE['lastVisit']))
        $visit = $_COOKIE['lastVisit'];
else
        echo "You've got some stale cookies!";
echo "Your last visit was - ". $visit;
?>

This handy script first uses the isset function to be sure that our “lastVisit” cookie still exists on the user’s PC, if it does, then the user’s last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this:

Display:

Your last visit was – 11:48 – 02/28/08

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users:

  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

This chapter will teach you how to set cookies, how to access them and how to delete them.

The Anatomy of a Cookie:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
                 path=/; domain=test.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser’s headers might look something like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: test.domen.co.in:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].

Setting Cookies with PHP:

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

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments:

  • Name – This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value –This sets the value of the named variable and is the content that you actually want to store.
  • Expiry – This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path –This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain – This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security – This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age these cookies will be expired after one hour.

<?php
   setcookie("name", "Taiijas", time()+3600, "/","", 0);
   setcookie("age", "27", time()+3600, "/", "",  0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>

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

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
  if( isset($_COOKIE["name"]))
    echo "Welcome " . $_COOKIE["name"] . "<br />";
  else
    echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired:

<?php
  setcookie( "name", "", time()- 60, "/","", 0);
  setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

 

PHP Sessions – Why Use Them?

As a website becomes more sophisticated, so must the code that backs it. When you get to a stage where your website need to pass along user data from one page to another, it might be time to start thinking about using PHP sessions.

A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. This makes it quite a problem for tasks like a shopping cart, which requires data(the user’s selected product) to be remembered from one page to the next

PHP Sessions – Overview

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

It is important to ponder if the sessions’ temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.

Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users’ data from getting confused with one another when visiting the same webpage.

Note:If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug.

Starting a PHP Session

Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.

PHP Code:

<?php
session_start(); // start up your PHP session!
?>

This tiny piece of code will register the user’s session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user’s session.

Storing a Session Variable

When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.

PHP Code:

<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>

Display:

Pageviews = 1

In this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.

PHP Sessions: Using PHP’s isset Function

Now that you are able to store and retrieve data from the $_SESSION array, we can explore some of the real functionality of sessions. When you create a variable and store it in a session, you probably want to use it in the future. However, before you use a session variable it is necessary that you check to see if it exists already!

This is where PHP’s isset function comes in handy. isset is a function that takes any variable you want to use and checks to see if it has been set. That is, it has already been assigned a value.

With our previous example, we can create a very simple pageview counter by using isset to check if the pageview variable has already been created. If it has we can increment our counter. If it doesn’t exist we can create a pageview counter and set it to one. Here is the code to get this job done:

PHP Code:

<?php
session_start();
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+ 1;
else
    $_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
?>

The first time you run this script on a freshly opened browser the if statement will fail because no session variable views would have been stored yet. However, if you were to refresh the page the if statement would be true and the counter would increment by one. Each time you reran this script you would see an increase in view by one.

Cleaning and Destroying your Session

Although a session’s data is temporary and does not require that you explicitly clean after yourself, you may wish to delete some data for your various tasks.

Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart.

PHP Code:

<?php
session_start();
if(isset($_SESSION['cart']))
    unset($_SESSION['cart']);
?>

You can also completely destroy the session entirely by calling the session_destroy function.

PHP Code:

<?php
session_start();
session_destroy();
?>

Destroy will reset your session, so don’t call that function unless you are entirely comfortable losing all your stored session data!

PHP Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Bore using any session variable make sure you have setup this path.

When a session is started following things happen:

  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.

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

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

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

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

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

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

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

<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:

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

Here is the example to unset a single variable:

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

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

<?php
   session_destroy();
?>

Turning on Auto Session:

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

Sessions without cookies:

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

<?php
   session_start();
   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

PHP Introduction Day 1 Day 2 Day 3 Day 4 Day 5