BDI Logo

Introduction to PHP

Class 4

HTTP Requests

Laptop and server connected via the internet

Photo credits: Andrew E. Larson and John Seb Barber cc

HTTP Requests

  • HTTP (Hypertext Transfer Protocol) is a way browsers and servers communicate
  • It's the most common communication protocol on the web. That's why web addresses start with http://
  • The most common types of requests are GET and POST. GET requests data from a specific resource. POST submits data to a specified resource.
  • When you send a PHP server a GET or POST request, you can use PHP to capture some information from the request.

GET vs. POST

GET

  • GET requests include all information in the URL, and can be bookmarked
  • GET requests are visible to everyone.
  • GET requests are good for showing different information on the same template.

POST

  • POST requests send information as part of a the request directly. They can't be bookmarked
  • POST requests are invisible to others.
  • POST requests are great for forms.

Let's Develop It

We're going to practice retrieving data from requests to gather information from your users. We'll need a few more files.Download a copy of today's practice files and unzip them directly into your gdi folder.

User Input

Comment box

Photo credit: Rym DeCoster cc

URL Parameters

You use URL parameters to send information via GET request. URL parameters go at the end of a URL. Parameters use the form ?var1=val1&var2=val2&.... For example, you could send a first and last name like this:

http://example.com/index.php?firstname=ada&lastname=lovelace

Super Globals

Remember global and local variables? PHP has a special class of variables called superglobals. Superglobals are built-in variables that are always available in all scopes. $_GET is a superglobal that contains all the information from a GET request.

Using $_GET

To retrieve the first name and last name values from this url:

http://example.com/index.php?firstname=ada&lastname=lovelace

You can use $_GET

$firstName = htmlspecialchars($_GET["firstname"]);
$lastName = htmlspecialchars($_GET["lastname"]);

Using $_GET["urlparameter"] retrieves the value from the $_GET superglobal. The function htmlspecialchars is a built-in function to help clean up user data.

Let's Develop It

Let's practice using $_GET.

  1. Go to the cats list page. You should see a list of cat names, with links.
  2. Hover over one of the links. You should see a long URL, like this: catdetails.php?name=Caramel&furcolor=Calico&age=3&personality=Sweet.
  3. Click on a link. It will take you to a template page without any information.
  4. Open up catdeatils.php. Modify the code of this page to use the $_GET variable to retrieve the information from the URL and store it in variables.
  5. Display the variables in the table

HTML Forms

A simple HTML form may look something like this:

<form action="myform.php" method="post">
  <label for="question">A question?</label>
  <input type="text" name="question" maxlength="50">
  <input type="submit" id="formSubmit" value="Submit">
</form>

The action attribute tells the browser where to send the form. The method attribute tells the browser what type of HTTP request to use. In this case, when the user selects the submit button, the browser will send the form data to myform.php in a POST request.

Using $_POST

$_POST is a superglobal variable, just like $_GET. When a user submits a form, the $_POST variable will store information based on the name (not id!) of the HTML form field. So to retrieve data from this field:

<input type="text" name="question">

You would use this code:

$question = htmlspecialchars($_POST["question"]);

Using $_POST["fieldname"] retrieves the value from the $_POST superglobal.

Using POST on forms

There are two common ways to submit a form with PHP:

  1. Submit the form data to a seperate form-processing page, like a thank you or confirmation page.
  2. Submit the form to the same page the form is on.

Checking the request type

If you are submitting a form to the same PHP file, you can use an if statement to wrap your form-processing script:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  //Process the form data and display results
}

Let's Develop It

Using a sample form we'll process some user-submitted data. This is a big task. Work piece by piece and test as you go.

  1. Open the file myform.php and find the two fields on the form. The form submits to the same page using POST
  2. Add code to retrieve data from the form. Don't forget your if statement!
  3. Add code to calculate the final bill
  4. Add code to display the results somewhere on the page

Cookies

Cookies on a computer keyboard

Photo credit: Theo Crazzolara cc

Cookies

  • A cookie is small piece of data stored on a user's computer
  • Each time the same browser requests a page, it will send the cookie too
  • Often used to track data like logins or shopping carts
  • The user's browser must voluntarily accept the cookie. The browser settings control this.

Cookies in PHP

PHP has built in features to set and read cookies. This uses a special superglobal, $_COOKIE. When we add vaues to this superglobal, PHP will also send the cookie to the user's computer.

Setting Cookies

The basic values used to set a cookie are:

  • Name: The name of the cookie. Usually something like user or cart
  • Value: The value of the cookie, such a user's id or cart number
  • Expire: When the cookie should be deleted from the user's computer
  • Path: What parts of the site it should apply to. / means the entire site, /folder will only apply in that directory

Setting Cookies

The basic syntax is:

setcookie(name, value, expire, path)

For example:

$cookie_name = "username";
$cookie_value = "Grace Hopper";
$cookie_time = time() + (86400 * 30); /*The current time, plus 30 days.
The time stamp is in seconds, and there are 86400 seconds in one day*/
setcookie($cookie_name, $cookie_value, $cookie_time, "/");

Reading Cookies

We can use the isset() function to check to see if cookies exist. If they do, we can retrieve the information from the superglobal.

if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named $cookie_name is not set!";
} else {
    echo "Cookie $cookie_name is set!<br />";
    echo "Value is: " . $_COOKIE[$cookie_name];
}

Let's Develop It

Set a cookie on one of your pages. Then see if you can retrieve the value on a different page.

You did it!

Man jumping in air

Photo credit: sunface13 cc

Resources

  • PHP Manual, the official PHP documentation. Check the comments; they are useful.
  • Code Academy, with interactive PHP lessons to help you review.