PHP - My SQL (Chapter - 7: PHP Form Interaction)

Superglobals, Getting & Posting Form Field Data, File Uploads, Sessions

1. Predefined Variables & Superglobals


We already discussed variables, but we did not already discuss the variables that come ready-made in PHP. Predefined variables are already defined, as their name implies, and can be used without you having to create them first.

The majority of predefined variables are used to provide information from and about the web server, the web browser, and the user. They are called superglobals.

The following superglobals are available:


Variable Name Variable Description
$_GET HTTP GET Variables
$_POST HTTP POST Variables
$_FILES HTTP File Upload Variables
$_SERVER Server And Environment Information
$_COOKIE HTTP Cookies
$_SESSION Session Variables
$_REQUEST HTTP Request Variables
$GLOBALS References All Variables In A Global Scope
$php_errormsg The Previous (Last) Error Message

We will discuss many of these superglobals in detail on the following pages, so for now we will only briefly demonstrate how they are used with a demonstration of the $_SERVER superglobal.


<?php
     echo "Your IP Address Is: " . $_SERVER['REMOTE_ADDR'] . "<br>";
     echo "The Current Page Name Is: " . $_SERVER['PHP_SELF'] . "<br>";
    echo "You Came From A Page Called: " . $_SERVER['HTTP_REFERER'] . "<br>";
?>

Superglobals, such as the $_SERVER variable, are arrays, which we have not yet learned about. The are a single variable that contain multiple values, all of which are separate and can be referenced separately. The brackets and single quotes at the end of the variable contain the reference name of the real value that we want. The result of the above example is:


Your IP Address Is: 118.95.83.16
The Current Page Name Is: /course/somefilename.php
You Came From A Page Called: http://www.binitpatel.co.in/course/somepagename.php

The $_SERVER variable has over thirty elements available, most of which are actually useful. The most common elements, assuming your server supports them, are:


Variable Description
$_SERVER['PHP_SELF'] The filename of the currently executing script, relative to the document root.
$_SERVER['SERVER_ADDR'] The IP address of the server under which the current script is executing.
$_SERVER['SERVER_NAME'] The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
$_SERVER['SERVER_SOFTWARE'] Server identification string, given in the headers when responding to requests.
$_SERVER['SERVER_PROTOCOL'] Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
$_SERVER['REQUEST_METHOD'] Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
$_SERVER['REQUEST_TIME'] The timestamp of the start of the request. Available since PHP 5.1.0.
$_SERVER['QUERY_STRING'] The query string, if any, via which the page was accessed.
$_SERVER['DOCUMENT_ROOT'] The document root directory under which the current script is executing, as defined in the server's configuration file.
$_SERVER['HTTP_CONNECTION'] Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
$_SERVER['HTTP_HOST'] Contents of the Host: header from the current request, if there is one.
$_SERVER['HTTP_REFERER'] The address of the page (if any) which referred the user agent to the current page.
$_SERVER['HTTP_USER_AGENT'] This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).
$_SERVER['HTTPS'] Set to a non-empty value if the script was queried through the HTTPS protocol.
$_SERVER['REMOTE_ADDR'] The IP address from which the user is viewing the current page.
$_SERVER['REMOTE_HOST'] The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
$_SERVER['REMOTE_PORT'] The port being used on the user's machine to communicate with the web server.
$_SERVER['SCRIPT_FILENAME'] The absolute pathname of the currently executing script.
$_SERVER['SERVER_ADMIN'] The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file.
$_SERVER['SERVER_PORT'] The port on the server machine being used by the web server for communication. For default setups, this will be '80'.
$_SERVER['SERVER_SIGNATURE'] String containing the server version and virtual host name which are added to server-generated pages, if enabled.
$_SERVER['PATH_TRANSLATED'] Filesystem based path to the current script.
$_SERVER['SCRIPT_NAME'] Contains the current script's path. This is useful for pages which need to point to themselves.
$_SERVER['REQUEST_URI'] The URI which was given in order to access this page; for instance, '/index.html'.
$_SERVER['PHP_AUTH_DIGEST'] When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client.
$_SERVER['PHP_AUTH_USER'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
$_SERVER['PHP_AUTH_PW'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
$_SERVER['AUTH_TYPE'] When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.

2. Getting Form Field Data


Obtaining information that is entered into an HTML form is actually a simple process using PHP. All you need to know is the method used to send the form data, the name of each form field, and what you want to do with the information that you obtain.

When the form method used is "get", the information entered into the form is sent via the URL when the form is submitted. It is visible to everyone, and limited to 100 characters.

Using the $_GET superglobal along with the name of the form field, we can obtain the value of each field.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
     Type In Something: <input name="txt1" type="text" size="25">
     <input type="submit" value="Submit">
</form>

<?php
     echo "You Typed: " . $_GET['random-info'];
?>

As you can see, the results of these functions can be echoed, stored in a variable, etc.Type In Something:          


Obviously, using the GET method is limiting in both size and security, so use it wisely. It is useful if you want to allow your users to bookmark a page to come back to later, because they will be returned to the page with the same information already submitted.

3. Posting Form Field Data


The method of obtaining information that is entered into an HTML form using the POST method is nearly identical to obtaining information that uses the GET method. The only difference? The spelling!

When the form method used is "post", the information entered into the form is sent behind-the-scenes when the form is submitted. It is not visible in the address bar, but it is limited to 8MB in size. (Don't worry about the limit; that's a LOT of data!).

Using the $_POST superglobal along with the name of the form field, we can obtain the value of each field.


<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
     Type In Something: <input name="txt1" type="text" size="25">
     <input type="submit" value="Submit">
</form>

<?php
     echo "You Typed: " . $_GET['random-info'];
?>

If you tried the demo above you will see that the HTML form, when submitted, uses $_SERVER['PHP_SELF'] to send you right back to the page that the form was submitted from. If you had typed anything into the form, it is echoed directly onto the page.

This method is used for the majority of form-related tasks.

4. Getting & Posting Checkbox & Radio Button Results


Obtaining data from radio buttons and checkboxes can be a little tricky, generally due to a lack of understanding of how radio buttons and checkboxes work.

It is important to remember two facts:

  • Checkbox "Names" Must Be Unique to Each Checkbox
  • Radio Button "Names" Must Be Identical For Each Group of Buttons

Let's jump right into an example:


<form action="php-forms-get-post-checkbox-radio-data.php" method="post">
     Why don't they play poker in the jungle?<br>
     <input type="radio" name="jungle" value="treefrog"> Too many tree frogs.<br>
    <input type="radio" name="jungle" value="cheetah"> Too many cheetahs.<br>
    <input type="radio" name="jungle" value="river"> Too many rivers.<br><br>

    Check the box if you want your answer to be graded:
    <input type="checkbox" name="grade" value="yes"><br><br>

    <input type="submit" name="submit" value="Submit"><br>
</form>

The code produces the following result:


Why don't they play poker in the jungle?
 Too many tree frogs.
 Too many cheetahs.
 Too many rivers.

Check the box if you want your answer to be graded:


Now let's use the $_POST[] superglobal to get the form data that was submitted. It is best to begin by checking to see if the form was submitted. This can be done using the isset() function to see if the submit button has been clicked.


<?php
    if (isset($_POST['submit'])) { /* Do Something Here */ }
     else { echo "Please submit the form."; }
?>

As you can see, the name of each $_POST[] superglobal corresponds with the name of the HTML form field in question.

Next, we can check to see if the submitted form should be graded. Checkboxes only return a value if they are checked. If a checkbox is not checked, then no value will be sent, so we can use the empty() function to determine our next course of action.


<?php
    if (isset($_POST['submit'])) {
         if (!empty($_POST['grade'])) { /* Grade the question. */ }
        else { echo "Your answer will not be graded."; }
    } else { echo "Please submit the form."; }
?>

Now we can find out which answer was chosen.


<?php
     if (isset($_POST['submit'])) {
         if (!empty($_POST['grade'])) {
              if (!empty($_POST['jungle'])) { /* Get Radio Button Value */ }
              else { echo "You did not choose an answer."; }
         } else { echo "Your answer will not be graded."; }
    } else { echo "Please submit the form."; }
?>

And at last, we can determine whether or not it was the right answer.


<?php
     if (isset($_POST['submit'])) {
        if (!empty($_POST['grade'])) {
            if (!empty($_POST['jungle'])) {
                 if ($_POST['jungle']=="cheetah") { echo "You got the right answer!"; }
                else { echo "Sorry, wrong answer."; }
            } else { echo "You did not choose an answer."; }
        } else { echo "Your answer will not be graded."; }
    } else { echo "Please submit the form."; }
?>

Submit the form in the example at the top of the page to see the results below. (Notice that the form action will return you to this page when the form is submitted.)


Please submit the form.

5. PHP File Uploads


Allowing anyone and everyone to upload files to your web server opens up many, many concerns about security, but we will not address them all here. Instead, we will focus on the very basic mechanics of uploading files so that you can experiment with this feature.

To begin, you will need an HTML file upload form with a method of "post" and a specific encoding type, such as the following example. (The action should lead to the php file where the file upload script is located.)


<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="my-file" size="50" maxlength="25"> <br>
    <input type="submit" name="upload" value="Upload">
</form>

When a file is uploaded, it gets stored in a temporary area on the server until it is moved. The file has to be moved from that area, or else it will be destroyed. In the meantime, the $_FILES[] superglobal array is filled up with data about the uploaded file. Since the file's upload field in our example is called "my-file", the following data is created:


Superglobal Description
$_FILES['my-file']['name'] Original Name of File Before It Was Uploaded
$_FILES['my-file']['type'] The MIME Type of File, Provided By the Browser
$_FILES['my-file']['size'] Size of the File (In Bytes)
$_FILES['my-file']['tmp_name'] Location of Temporary File on Server
$_FILES['my-file']['error'] Any Error Codes Resulting From the File Upload

To begin the file upload script, we will use the is_uploaded_file() function as an alternative to the isset() and empty() functions to verify that a file has been uploaded to its temporary location.


<?php
    if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
         echo "The file was uploaded successfully but has not been saved.<br>";
        echo "The file is temporarily stored: " . $_FILES['my-file']['tmp_name'] . "<br>";
        echo "The file name was: " . $_FILES['my-file']['name'] . "<br>";
        echo "The file type is: " . $_FILES['my-file']['type'] . "<br>";
        echo "The file size is: " . $_FILES['my-file']['size'] . "<br>";
    } else {
        echo "The file was not uploaded successfully.";
        echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
    }
?>

The next step, if you want to only accept certain file types and sizes, would be to check out those factors and send out error messages accordingly. In our example we'll move right along and determine whether or not the file has already been uploaded, since we do not want to over-write an existing file. We can use the file_exists() function for this purpose.


<?php
    if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
        $path = '/html/binitpatel.co.in/uploads/' . $_FILES['my-file']['name'];
        if (!file_exists($path)) {
            echo "File does not exist. It is safe to move the temporary file.";
        } else {
            echo "File already exists. Please upload another file.";
        }
    } else {
        echo "The file was not uploaded successfully.";
        echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
    }
?>

And now, at long last, we can use the move_uploaded_file() function to move the temporary file into its permanent location.


<?php
    if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
         $path = '/html/binitpatel.co.in/uploads/' . $_FILES['my-file']['name'];
         if (!file_exists($path)) {
            if (move_uploaded_file($_FILES['my-file']['tmp_name'], $path)) {
                echo "The file was uploaded successfully.";
            } else {
            echo "The file was not uploaded successfully.";
        }
    } else {
        echo "File already exists. Please upload another file.";
    }
    } else {
        echo "The file was not uploaded successfully.";
        echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
    }
?>

That's all it takes!

Two common problems that you may run into, causing the upload process to fail, are the file size and directory permissions. PHP sets a default "upload_max_filesize" to limit the size of the file uploaded. The default is 2M (megabytes) and any file that exceeds this limit will not upload. Also, if the directory (folder) where you try to move the file must have certain permissions set, or you will not be allowed to move the file into that directory.

6. PHP Url Functions


PHP provides several functions used to deal with URL strings. A URL is an address used to identify a website, and a URL string might look something like this: http://www.binitpatel.co.in/Chapter-7.aspx The URL functions that we will learn about here are:


Function Description
get_headers() Fetches all the headers sent by the server in response to a HTTP request
get_meta_tags() Extracts all meta tag content attributes from a file and returns an array
parse_url() Parse a URL and return its components
urlencode() URL-encodes string
urldecode() Decodes URL-encoded string
rawurlencode() URL-encode according to RFC 1738
rawurldecode() Decode URL-encoded strings

Am I the only one that wants all that translated into English?! Let's begin with get_headers(), which will return an array containing the headers sent by the server in response to an HTTP request.


Example Code:
<?php
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        // Example: http://www.binitpatel.co.in/Chapter-7.aspx
    $headers = get_headers($url);
    print_r($headers);
?>

Result (Array Created):
    Array (
        [0] => HTTP/1.1 200 OK
        [1] => Date: Sun, 13 July 2014 22:30:39 GMT
        [2] => Server: Apache/2.2.3 (CentOS)
        [3] => X-Powered-By: PHP/5.1.6
        [4] => Set-Cookie: PHPSESSID=ggnc33i24gukchi5iqnqg8b4a7; path=/
        [5] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
        [6] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
        [7] => Pragma: no-cache
        [8] => Vary: Accept-Encoding
        [9] => Content-Length: 6746
        [10] => Connection: close
        [11] => Content-Type: text/html
        [12] => Content-Language: en
)

..ooookkkkaaayyy... moving on (to something more useful?), the get_meta_tags() function returns an array containing the meta tags found between the HTML <head> and </head> tags of the specified webpage.


Example Code:
<?php
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        // Example: http://www.binitpatel.co.in/Chapter-7.aspx
    $MetaTags = get_meta_tags($url);
    print_r($MetaTags);
?>

    Result (Array Created):
        Array (
        [description] => Free Tutorial On PHP Url Functions At binitpatel.co.in
        [keywords] => php, tutorial, learn, free, url, functions
)

The parse_url() functions takes a url and returns it to you in little pieces stored in an array.


Example Code:
<?php
    $url = "http://www.binitpatel.co.in/Chapter-7.aspx/?question=testing-testing";
    $ParsedUrl = parse_url($url);
    print_r($ParsedUrl);
?>

Result (Array Created):
    Array (
        [scheme] => http
        [host] => www.binitpatel.co.in
        [path] => Chapter-7.aspx
        [query] => question=testing-testing
)

The urlencode() and rawurlencode() functions both encode strings by replacing all non-alphanumeric characters such as spaces and symbols with placeholders that can later be decoded to return the original string. These functions are ideal for preserving strings used in URL queries, or even passed between pages as "GET" data when a form is submitted.

The urldecode() and rawurldecode() functions can be used to decode the strings once they reach their destination and need to be used or displayed in their original format.

The urlencode() function works with urldecode() and the rawurlencode() function works with rawurldecode(). The difference between the two sets of functions is only in the style that they used to encode each string.


Example Code:
<?php
    $string1 = "What is a mouse's favorite game?";
    $result = urlencode($string1);
    echo $result . "<br />";
    $result = urldecode($string1);
    echo $result . "<br />";
    $string2 = "Hide and squeak!";
    echo rawurlencode($string2);
    echo rawurldecode($string2);
?>

Result of urlencode() and urldecode():
    What+is+a+mouse%27s+favorite+game%3F
    What is a mouse's favorite game?

Result of rawurlencode() and rawurldecode():

    Hide%20and%20squeak%21
    Hide and squeak!

7. Cookies Vs. Sessions


Before we learn how to create cookies and sessions it is important to understand the difference between these two similar (and yet very different) methods of storing information. And before we begin to explain that, let's get one very important detail out of the way; the kind of cookies that we will be discussing are no more edible than my keyboard. (And yes, my keyboard is plastic.)

The basic task of both cookies and sessions is to store visitor data so that it can be accessed by every page on a website. This data is usually provided by the visitor and used to customize the experience, including their visit statistics, identity, setting and/or preferences, etc.

  • Cookies are small files that are stored in the visitor's browser.
  • Cookies can have a long lifespan, lasting months or even years.
  • Cookies are limited in size depending on each browser's default settings.
  • Cookies can be disabled if the visitor's browser does not allow them (uncommon).
  • Cookies can be edited by the visitor. (Do not use cookies to store sensitive data.)
  • Sessions are small files that are stored on the website's server.
  • Sessions have a limited lifespan; they expire when the browser is closed.
  • Sessions are only limited in size if you limit their size on the server.
  • Sessions cannot be disabled by the visitor because they are not stored in the browser.
  • Sessions cannot be edited by the visitor.

In short, cookies serve as a temporary or long-term storage unit on the visitor's computer that should not contain sensitive information, and sessions serve as a temporary storage unit not on the visitor's computer that can hide sensitive information. For most tasks I find it efficient to use sessions and cookies together. By giving each visitor a cookie with a unique ID, I can use that cookie to recognize each visitor when they return. I can then use sessions to handle the page-to-page data exchange that actually provides each visitor with their customized settings and information, which are provided by each visitor and stored in a database until they are reference by the unique ID stored in the cookie. Now that's wasn't too hard to swallow, was it? But, now that you know the difference between sessions and cookies, feel free to skip over actually learning them, until you plan to use them... they are not yet vital knowledge.

8. PHP Cookies


Cookies are small files that are stored in the visitor's browser.Cookies can be used to identify return visitors, keep a user logged into a website indefinitely, track the time of the user's last visit, and much more.

Cookies accept seven different arguments, but only the "name" is required. (Keep in mind that all values are stored on the visitor's computer, so the data is not private. Never store passwords in cookies, for example!) The options are:


Argument Description
name Name of the Cookie
value Value of the Cookie
expire Time When Cookie Expires (Unix Timestamp) (If "0", Or Omitted, Cookie Will Expire When Browser Closes) (Set to Client's Time, Not Server's)
path Server Path Where Cookie Is Available (If Path Is the Root Directory, Cookie Is Available In Entire Domain) (Default Value Is Current Directory)
domain Domain That Cookie Is Available
secure Indicates That Cookie Should Only Be Transmitted Over a Secure HTTPS Connection From Client
httponly When TRUE, Cookie Is Only Accessible Through HTTP Protocol

PHP allows you to create, retrieve and update cookies. The setcookie() function is used to first create a cookie. This function must be run before any other data is sent to the browser, such as the opening <html> tag or random whitespace. The syntax is: setcookie(name, value, expire, path, domain);


<?php
    setcookie("Example", "Whatever Value I Want", time()+2592000);
?>

Here we have set a cookie called "Example" that has a useless value of "Whatever Value I Want" and an expiration date one month in the future. (We have not yet studied php date and time functions, so I will briefly clarify that the time() function collects the current timestamp and adds 2591000 seconds to it, which is 30 day's worth of seconds, thus creating an expiration date 30 days in the future.)

Now, we are free to retrieve the "value" that is stored in our cookie, using the $_COOKIE superglobal. It is best to use the isset() function for this, because if a cookie has not been set on the computer that we are trying to retrieve it from, headaches can result.


<?php
    if (isset($_COOKIE["Example"])) {
         echo $_COOKIE["Example"];
    } else {
        echo "No Cookie Named 'Example' Is Set";
    }
?>

Here we check to see if the cookie that we created really was created, and echo the value if it was. The value that will be echoed is "Whatever Value I Want". A more practical example might have stored the user's name or preferences, but it's fun to be unpredictable.

Deleting a cookie is as simple as using the setcookie() function with an expiration date in the past. Since there are 3600 seconds in an hour, using -3600 will set the expiration date an hour previous and the cookie will expire and disappear.


<?php
    setcookie("Example", "", time()-3600);
?>

Finally! A cookie that your mother won't limit your intake of!

9. PHP Sessions


Sessions are small, temporary files that are stored on the website's server. Sessions can be used to store unique information about, or change unique settings for each visitor, but only for the duration of each separate visit.

Sessions work by assigning each visitor a unique string that is used to identify them as they move from page to page. This prevents one visitor's information from being mixed up with another's.

PHP allows you to create and destroy a session, as well as assign, retrieve and update session variables. The session_start() function is used to first create a session, or to continue the current session if one already exists. This function must be run on every page, before any other data is sent to the browser, such as the opening <html> tag or random whitespace. The code is very simple.


<?php
     session_start();
?>

After starting the session you can store session variables in the $_SESSION superglobal, as well as update and retrieve them. Each value stored in this array is assigned a "key" or name by which to identify the specific value. The syntax is: $_SESSION['key'] = value;


<?php
    session_start();

    $_SESSION['question'] = 'What happens when you throw a green stone in the red sea?';

    $_SESSION['answer'] = 'It gets wet!';
?>

Due to the nature of sessions, you can assign a session value on one page and retrieve it on a completely separate page, as long as session_start() is set at the beginning of the file. The best practice is to check and see if each session value exists before retrieving it, by using the isset() function.


<?php
    session_start();

    if (isset($_SESSION['question']) && isset($_SESSION['answer'])) {
        echo $_SESSION['question'];
        echo $_SESSION['answer'];
    }
?>

Although sessions will end themselves and erase all session variables after a period of inactivity, it is possible to speed up the process. This is necessary if you are using sessions to keep a person logged into a website, for example, and they click "logout". The unset() function will free (erase) a specific session variable, and the session_destroy() function will end the session completely, as well as erase all session variables.


<?php
    unset($_SESSION['question']);
    unset($_SESSION['answer']);
    session_destroy();
?>

Continue to Index

Welcome to HoneyBee - The Learning Platform

By Binit Patel

HoneyBee is a learning platform which is an integrated set of informative online services that enable learners involved in education with information, tools and resources to support and enhance Teaching, Learning and Management.

Contact With Me