Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Example] Cookies, Sessions and PHP
#1
Here is a small example of what you can do with cookies and sessions.
It checks if a user has a cookie created by your script, if there is no cookie the code prints out a HTML form asking user for a secret word.
The user can submit a wrong word only 3 times, but in this code when s/hereaches thelimit, it is set back to o.

Can you eat the cookie?
No, ;)
A cookie is small string that is stored on the users computer by your script.
Cookies are used for tracking and transporting data from one page to other on your site.
They can be used for saving the current user information such as, Username, logged in time and everything that can be
placed in a string line.

NOTE: If you already didn't know a user is nowdays able to decide if he wants to allow cookies or not, if s/he doesn't allow the creation of a cookie the code posted here will not
work!
For this case we have the SESSIONS.

What are Sessions?

A Session is just same as a Cookie, but they can't be blocked by the user!
They are only temporary files, which are only existent while the user has s/hes browser open, and are deleted when the browser is closed.
The script I show you here uses to store a Cookie, because if we would use a Session, the user would need to input the secret word
everytime they restart the browser.

PHP Code:
<?php

/*****************************************************************************
    Cookies Session and PHP
    Author: MoTU
*****************************************************************************/

session_start();

if(isset(
$_GET['eat'])) {
    unset(
$_COOKIE['TUT_USER']);
}

if(isset(
$_POST['secret'])) {

    if(!isset(
$_SESSION['attempts'])) {
        
$_SESSION['attempts'] = 1;
    }elseif(
$_SESSION['attempts'] > 3) {
        unset(
$_SESSION['attempts']);
        die(
"You failed 3 times in row, please leave!!!");
    }
    
    if(
$_POST['key'] == "secretkey") {
        
setcookie("TUT_USER"md5($_SERVER['SERVER_ADDR']), time()+3600);
        echo 
"Welcome";
    }else{
        
$_SESSION['attempts']++;
        die(
"<a href=\"index.php\">Try again</a>");
    }
}

echo 
"<br />";


if(isset(
$_COOKIE['TUT_USER'])) {
    echo 
"You have recieved an Cookie; <a href=\"template.class.php?eat\">Eat it</a> or <a href=\"index.php\">Keep it</a>";
}else{
    echo <<<HTML
    <div>
        <form action="index.php" method="post">
            Secret Word:<input type="text" name="key" />
            <input type="submit" name="secret" value="Enter" />
        </form>
    </div>
HTML;
}

?>


I will skip the first IF block, $_GET['eat'] and talk about later.

We start off with start_session(), this function needs to be called before any headers were sent or any content was printed.
Otherwise you'll get an FATAL ERROR.

In the Line 12 the code checks if the user has submited the form, $_POST['secret'] (secret is the name of the Form submit button).
Inside of this IF block, we first check if a Session named "attempts" was created, and define it as "1" if it wasn't created.
Next we check if the Session value is over "3", in that case we delete it ( unset() ) and kill the script showing an error message.

If the above check didn't kill the script because of too many attempts, we check the input of the user and if it matches our "secretkey". $_POST['key'] (key = Form Input field)
If the user inputs "secretkey" we use setcookie() to store a cookie on his system, with the name "TUT_USER" and mp5 encoded ip as it's value.
The cookie is set to expire after 1 hour, time()+3600
In the end we Welcome the user.

NOTE: setcookie() must be same as start_session() run before any output to the site.

If the user input isn't same as our "secretkey", we icrease the $_SESSION['attempts'] by 1 and kill the script showing the error message.
Now the user has one attampt less.

Right at the last IF block, we use isset() to check if a Cookie was set, $_COOKIE['TUT_USER'] (create by the avobe setcookie() function).
If the user have a cookie from your domain and with the name "TUT_USER" we print out a message, otherwise we print the input form again!

Now back at the very first IF block, $_GET['eat'], here we check if a user wants to delete a cookie, a link is printed if a cookie was created as you can see.
And we use unset to delete the cookie.

More to read.....
http://www.php.net/manual/en/function.setcookie.php
http://www.php.net/manual/en/function.session-start.php
Reply
#2
Great tutorial, thanks! Smile
Reply
#3
I'm glad you like it and also hope that it helped you somehow! Big Grin
Reply
#4
Very well written and helpful Smile
Reply
#5
Thanks Spl3en...
I'm glad you like it! ;)
Reply
#6
Enjoy reading your tutorials, you manage to keep a focus point throughout, well planned and executed.
Many people will learn from this, well done fella.
Reply
#7
Thanks for this, it was very helpful indeed.
[Image: angelsig.jpg]


Reply
#8
Thanks for this tutorial!

It's really helpful!
Reply
#9
Wait, so I can't eat the cookie?
[Image: TYzKF.png]
Reply
#10
(12-20-2010, 07:18 AM)Orgy Wrote: Wait, so I can't eat the cookie?

babe I thought I picked up enough tacos for the week...


OT:

Nice tutorial.
(11-23-2010, 08:40 PM)Guest Wrote: Alright, did the 'Support' get removed from SupportForums?
You're not a good Emotional Helper.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PHP Framework List: An Ultimate Guide to 102 PHP Frameworks for Web Developers tk-hassan 0 766 07-27-2020, 11:26 PM
Last Post: tk-hassan
  PHP Video Tutorials (PHP For Beginners) Eleqtriq 4 3,253 10-10-2011, 01:00 PM
Last Post: Greyersting

Forum Jump:


Users browsing this thread: 1 Guest(s)