Let's Eat Cookie



In our Day 9 code (day_9_ex_1.php) we used POST method, so you won't be able to see the secret number server generated by looking at URL. But if you look source code of the page, you still able to see the secret number.

Viewing Source Code

You can view source code of any web page by pressing

Code:
CTRL+U


This will only show HTML code. It won't show any PHP code as PHP is running in server side.



From the source code, you can see the hidden INPUT field stores the secretNumber.

Code:
<input type="hidden" name="secretNumber" value="27">
How can we remove this number from the HTML code, so no one will be able to see it by viewing source code of our HTML page ? We can do this with the help of COOKIE.

What is COOKIE

Cookie is used to store information on visitors computer. Some sites can remember you, so you don't have to login to these site every time because they store a COOKIE on your computer, next time when you visit these sites, web server read the data stored in these COOKIE and authenticate you.

Data stored in cookie are more difficult to read (not impossible) for most users. Also most sites store encrypted value in the cooke, so even if someone read cookie, they won't be able to know what is stored in the cookie.

Let's make a script, that will store your name in cookie. Greet you when you visit the page again.

day_10_ex_1.php

PHP Code:
<?php

if (isset($_COOKIE['phpExpertName'])) {
    echo 
$_COOKIE['phpExpertName'] . ', Welcome to Bakery, eat some $_COOKIE';
    exit;
}

if (isset(
$_POST['phpExpertName']) && strlen($_POST['phpExpertName']) > 3) {
    
// time()+3600 = 1 hour, that is cookie will remember your name for 1 hour.
    // time() is a PHP function, that return current time in numeric format.
    // 3600 == number of seconds in 1 hour.
    // So to remember 2 hour, use time() + 3600 * 2
    
setcookie('phpExpertName'$_POST['phpExpertName'], time()+3600);
    echo 
'Cookie Set. Close the browser. Revisit this page, I will remember your name';
} else {

    echo 
'
        What is your name ?
        <form method="post" action="">
        <input type="text" name="phpExpertName">
        <button type="submit" name="whatever">Enter Web Site</button>
        </form>
    '
;
}
setcookie() function is used to set cookie. setcookie() must be called before any echo statement.

You will be able to read data stored in cookie using associative array $_COOKIE.

How to Delete A Cookie

A cookie can be delete by setting cookie expiry time to 0.

day_10_ex_2.php

PHP Code:
<?php

setcookie
('phpExpertName'''0);
echo 
'Cookie deleted.';
echo 
'<br>';
echo 
'Visit day_10_ex_1.php, you will see the script will ask you name again, because no cookie is set.';