PHP - tutorial - 07 - cookies, sessions, filters

revision:


PHP - cookies

The "setcookie()" function creates a cookie and must appear BEFORE the <html> tag.

The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers.

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value.

Syntax:

        setcookie(name, value, expire, path, domain, secure, httponly);
    

Parameter values:

name : required; specifies the name of the cookie;
value : optional; specifies the value of the cookie;
expire : optional; specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0.
path : optional; specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in.
domain : optional; specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain.
secure : optional; specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE.
httponly : optional; if set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE.

To skip an argument, the argument can be replaced by an empty string(“”).

We retrieve the value of the cookie "user" (using the global variable $_COOKIE) and use the isset() function to find out if the cookie is set.

The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received. To prevent URLencoding, use setrawcookie() instead.

examples:

create a cookie

                <;!DOCTYPE html>
                <;?php
                    setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
                ?>
                <;html>
                <;body>
                    <;?php
                        echo "cookie is created."
                    ?>
                    <;p>
                        <;strong>Note:<;/strong> 
                        You might have to reload the 
                        page to see the value of the cookie.
                    <;/p>
                
                <;/body>
                <;/html>    
            

check whether the cookie is set or not

                <!DOCTYPE html>
                <?php
                    setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
                ?>
                <html>
                <body>
                    <?php
                    if (isset($_COOKIE["Auction_Item"])){
                        echo "Auction Item is a  " . $_COOKIE["Auction_Item"];
                    }
                    else{
                        echo "No items for auction.";
                    }
                    ?>
                    <p>
                        <strong>Note:<;/strong>You might have to reload the page to see the value of the cookie.
                    </p>
                </body>
                </html>
            

access and modify the cookie value

                <!DOCTYPE html>
                <?php
                    $cookie_name = "user";
                    $cookie_value = "Alex Porter";
                    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
                ?>
                <html>
                <body>

                <?php
                    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];
                    }
                ?>
                </body>
                </html>
            

delete the cookie value ; set expireation date in the past

                <!DOCTYPE html>
                <?php
                    setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
                ?>
                <html>
                <body>
                    <?php
                        setcookie("Auction_Item", "", time() - 60);
                    ?>
                    <?php
                        echo "cookie is deleted"
                    ?>
                    <p>
                        <strong>Note:</strong>You might have to reload the page to see the value of the cookie.
                    </p>
                
                </body>
                </html>
            

PHP - sessions

Session variables store user information to be used across multiple pages (e.g. username, favorite color, etc).

By default, session variables last until the user closes the browser. Session variables hold information about one single user, and are available to all pages in one application.

A session is started with the session_start() function and session variables are set with the PHP global variable: $_SESSION.

The session_start() function must be the very first thing in your document, before any HTML tags. The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser.

The session IDs are randomly generated by the PHP engine .

The session data is stored on the server therefore it doesn't have to be sent with every browser request.

To change a session variable, just overwrite it. To remove all global session variables and destroy the session, use session_unset() and session_destroy().

start a PHP session and store session data

                <?php
                    session_start();
                    $_SESSION["Rollnumber"] = "11";
                    $_SESSION["Name"] = "Ajay";
                ?>
            
                <?php
                    // Start the session
                    session_start();
                    ?>
                    <!DOCTYPE html>
                    <html>
                    <body>

                    <?php
                    // Set session variables
                    $_SESSION["favcolor"] = "green";
                    $_SESSION["favanimal"] = "cat";
                    echo "Session variables are set.";
                ?>

                </body>
                </html>
            

access session data

                <?php
                    session_start();
                    echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>'; 
                    echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';
                ?>

                <?php
                    session_start();
                ?>
                <!DOCTYPE html>
                <html>
                <body>

                <?php
                    // Echo session variables that were set on previous page
                    echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
                    echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
                ?>
                </body>
                </html>
            

destroy certain session data or modify session variable

                <?php
                   session_start();
                   if(isset($_SESSION["Name"])){
                       unset($_SESSION["Rollnumber"]);
                   }
                ?>

                <?php   
                    session_start();
                ?>
                <!DOCTYPE html>
                <html>
                <body>

                <?php
                    // to change a session variable, just overwrite it
                    $_SESSION["favcolor"] = "yellow";
                    print_r($_SESSION);
                ?>
                </body>
                </html>
            

destroy complete session

                <?php
                    session_start();
                    session_destroy();
                ?>
             
                <?php
                    session_start();
                ?>
                <!DOCTYPE html>
                <html>
                <body>

                <?php
                    // remove all session variables
                    session_unset();

                    // destroy the session
                    session_destroy();
                ?>

                </body>
                </html>
            

PHP - filters

PHP filters are used to validate and sanitize external input.

Validating data = determine if the data is in proper form.
Sanitizing data = remove any illegal character from the data.
The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.

PHP - filter functions

These are used to validate and filter data coming from insecure sources, like user input. The behavior of these functions is affected by settings in php.ini.

filter_list() - returns a list of all supported filter names. It can be used to list what the PHP filter extension offers.

Filter Name Filter ID
int257
boolean258
float259
validate_regexp272
validate_domain277
validate_url273
validate_email274
validate_ip275
validate_mac276
string513
stripped513
encoded514
special_chars515
full_special_chars522
unsafe_raw516
email517
url518
number_int519
number_float520
add_slashes523
callback1024
code:
                <table>
                    <tr>
                        <td>Filter Name</td>
                        <td>Filter ID</td>
                    </tr>
                    <?php
                        foreach (filter_list() as $id =>$filter) {
                            echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
                        }
                    ?>
                </table>
                <style>
                    table, th, td { border: 0.2vw solid black;  border-collapse: collapse;}
                    th, td {padding: 0.5vw;}

                </style>
            

You should always validate external data! Invalid submitted data can lead to security problems and break your webpage! By using PHP filters you can be sure your application gets the correct input!

filter_var(var, filtername, options) - filters a single variable with a specified filter. It takes two pieces of data: the variable you want to check; the type of check to use. The filter_var() function can be used to:

sanitize a tring

example:

Hello World!
code:
                <?php
                    $str = "<h1>Hello World!</h1>";
                    $newstr = filter_var($str, FILTER_SANITIZE_STRING);
                    echo $newstr;
                ?>
            

validate an integer

example:

Integer is valid
Integer is valid
code:
                <?php
                    $int = 100;
                    if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
                        echo("Integer is valid");
                    } else {
                        echo("Integer is not valid");
                    }  
                ?>
                <?php
                    echo '<br>';
                    $int = 0;
                    if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) {
                    echo("Integer is valid");
                    } else {
                    echo("Integer is not valid");
                    }
                ?>      
            

validate an IP address

example:

127.0.0.1 is a valid IP address
code:
                <?php
                    $ip = "127.0.0.1";
                    if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
                    echo("$ip is a valid IP address");
                    } else {
                    echo("$ip is not a valid IP address");
                    }
                ?>
            

sanitize and validate an email address

example:

john.doe@example.com is a valid email address
code:
                <?php
                    $email = "john.doe@example.com";
                    // Remove all illegal characters from email
                    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
                    // Validate e-mail
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                        echo("$email is a valid email address");
                    } else {
                        echo("$email is not a valid email address");
                    }  
                ?>
            

sanitize and validate a URL

example:

https://www.lwitters.com is a valid URL
code:
                <?php
                    $url = "https://www.lwitters.com";
                    // Remove all illegal characters from a url
                    $url = filter_var($url, FILTER_SANITIZE_URL);
                    // Validate url
                    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
                        echo("$url is a valid URL");
                    } else {
                        echo("$url is not a valid URL");
                    }       
                ?>
            

filter_has_var(type, variable) - checks whether a variable of a specified input type exist.

example:

Email not found
code:
                <?php
                    if (!filter_has_var(INPUT_GET, "email")) {
                        echo("Email not found");
                    } else {
                        echo("Email found");
                    }
                ?>      
            

filter_id(filter_name) - returns the filter ID of a specified filter name.

example:

274
code:
                <?php
                    echo(filter_id("validate_email"));
                ?>
            

filter_input() - gets an external variable (e.g. from form input) and optionally filters it.

example:

E-mail:
code:
                <div>
                    <form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
                        E-mail: <input type="text" name="email">
                        <input type="submit" name="submit" value="Submit"> 
                    </form>
                    <?php
                    if (isset($_GET["email"])) {
                        if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) {
                            echo("Email is valid");
                        } else {
                            echo("Email is not valid");
                        }
                    }
                    ?>
                </div>  
            

filter_input_array() - gets external variables (e.g. from form input) and optionally filters them.

code:
                <?php
                    $filters = array (
                        "name" => array ("filter"=>FILTER_CALLBACK,
                                                "flags"=>FILTER_FORCE_ARRAY,
                                                "options"=>"ucwords"
                                                ),
                        "age"   => array ( "filter"=>FILTER_VALIDATE_INT,
                                                    "options"=>array("min_range"=>1,"max_range"=>120)
                                                ),
                        "email" => FILTER_VALIDATE_EMAIL
                        );
                    print_r(filter_input_array(INPUT_POST, $filters));
                ?>      
            

filter_var_array() - gets multiple variables and filter them.

array(3) { ["fullname"]=> string(13) "Peter Griffin" ["age"]=> string(2) "41" ["email"]=> string(17) "peter@example.com" }
code:
                <?php
                    $data = array(
                        'fullname' => 'Peter Griffin',
                        'age' => '41',
                        'email' => 'peter@example.com',
                    );

                    $mydata = filter_var_array($data);
                    var_dump($mydata);

                ?>      
            

PHP - predefined filter constants

INPUT_POST - POST variables;
INPUT_GET - GET variables;
INPUT_COOKIE - COOKIE variables;
INPUT_ENV - ENV variables;
INPUT_SERVER - SERVER variables;
FILTER_DEFAULT - do nothing, optionally strip/encode special characters. Equivalent to FILTER_UNSAFE_RAW;
FILTER_FLAG_NONE - allows no flags;
FILTER_FLAG_ALLOW_OCTAL - only for inputs that starts with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7;
FILTER_FLAG_ALLOW_HEX - only for inputs that starts with 0x/0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9;
FILTER_FLAG_STRIP_LOW - strip characters with ASCII value lower than 32;
FILTER_FLAG_STRIP_HIGH - srip characters with ASCII value greater than 127;
FILTER_FLAG_ENCODE_LOW - encode characters with ASCII value lower than 32;
FILTER_FLAG_ENCODE_HIGH - encode characters with ASCII value greater than 127;
FILTER_FLAG_ENCODE_AMP - encode &;
FILTER_FLAG_NO_ENCODE_QUOTES - do not encode ' and ";
FILTER_FLAG_EMPTY_STRING_NULL - not in use;
FILTER_FLAG_ALLOW_FRACTION - allows a period (.) as a fractional separator in numbers;
FILTER_FLAG_ALLOW_THOUSAND - allows a comma (,) as a thousands separator in numbers;
FILTER_FLAG_ALLOW_SCIENTIFIC - allows an e or E for scientific notation in numbers;
FILTER_FLAG_PATH_REQUIRED - the URL must contain a path part;
FILTER_FLAG_QUERY_REQUIRED - the URL must contain a query string;
FILTER_FLAG_IPV4 - allows the IP address to be in IPv4 format;
FILTER_FLAG_IPV6 - allows the IP address to be in IPv6 format;
FILTER_FLAG_NO_RES_RANGE - fails validation for the reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4, and for the reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10;
FILTER_FLAG_NO_PRIV_RANGE - fails validation for the private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16, and for the IPv6 addresses starting with FD or FC;
FILTER_FLAG_EMAIL_UNICODE - allows the local part of the email address to contain Unicode characters;
FILTER_REQUIRE_SCALAR - the value must be a scalar;
FILTER_REQUIRE_ARRAY - the value must be an array;
FILTER_FORCE_ARRAY - treats a scalar value as array with the scalar value as only element;
FILTER_NULL_ON_FAILURE - return NULL on failure for unrecognized boolean values;
FILTER_VALIDATE_BOOLEAN - validates a boolean;
FILTER_VALIDATE_EMAIL - validates value as a valid e-mail address;
FILTER_VALIDATE_FLOAT - validates value as float;
FILTER_VALIDATE_INT - validates value as integer;
FILTER_VALIDATE_IP - validates value as IP address;
FILTER_VALIDATE_IP - validates value as IP address;
FILTER_VALIDATE_MAC - validates value as MAC address;
FILTER_VALIDATE_MAC - validates value as MAC address;
FILTER_VALIDATE_REGEXP - validates value against a regular expression;
FILTER_VALIDATE_URL - validates value as URL;
FILTER_SANITIZE_EMAIL - removes all illegal characters from an e-mail address;
FILTER_SANITIZE_ENCODED - removes/Encodes special characters;
FILTER_SANITIZE_MAGIC_QUOTES - apply addslashes();
FILTER_SANITIZE_NUMBER_FLOAT - remove all characters, except digits, +- signs, and optionally .,eE;
FILTER_SANITIZE_NUMBER_INT - removes all characters except digits and + - signs;
FILTER_SANITIZE_SPECIAL_CHARS - removes special characters;
FILTER_SANITIZE_STRING - removes tags/special characters from a string;
FILTER_SANITIZE_STRIPPED - alias of FILTER_SANITIZE_STRING;
FILTER_SANITIZE_URL - removes all illegal character from a URL;
FILTER_UNSAFE_RAW - do nothing, optionally strip/encode special characters;
FILTER_CALLBACK - call a user-defined function to filter data;