Jump to content

  •  

Photo
- - - - -

P10: Passing Variables P4 COOKIES

PHP4Beginners

  • Please log in to reply
No replies to this topic

#1 DraxxTV

DraxxTV

    Member

  • SuperGeek
  • PipPip
  • 14 posts

Posted 06 July 2014 - 11:01 PM

COOKIES

A Cookie is a small file that is stored on a person's machine and is often used to help identify a user. When a person visits a page, the cookie is sent alone by the browser and then read by the server. Common uses for this are to tell if someone is logged in or to store information about their account preferences. When a cookie is sent and received, it is automatically URLEncoded (this can be prevented). The limits on the size of a cookie and the amount of data which can be stored is dependent on the browser the user is using.

Creating a Cookie

When it comes to using a cookie, the first thing you have to do is to actually create one. This is quite simple. All you have to do is the following

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

As you can see, there are different parameters within the setcookie function so we shall go through and talk about them all and how you can set them all.

Name

The name parameter basically covers what you want you want to name your cookie. To name this, you simply put what you would like to name it as in quotations.

setcookie("YourCookieName", value, expire, path, domain);

Please note that you cannot have things like spaces inside the name of your cookie.

Value

The value is the data for which you would like to store inside the cookie. You can store all kinds of data but you need to make sure not to store to much in there as it could make web browsing rather slow for the user. Also, when you store information in a cookie, it is stored as clear text so that the user can actually view the contents of this if they know where to look. This is why it is important not to store personal information in cookies or something important as it can easily be forged by a hacker to gain access to your systems. If you do plan on storing certain information then make sure that you encrypt it. You can set it like this:

setcookie("YourCookieName", "The data you would like to store inside the cookie!", expire, path, domain);

Expire

The Expire parameter is when you want a cookie to expire. This basically tells the browser when do delete the file on the users machine. So, if you have a login form and when you enter your username and password etc, the way it usually keeps you logged in is by storing your information inside a cookie.. A browser will then keep you logged in for a period of time. That time is controlled by the expire time. The way this is set may not be as straightforward as you would hope. Using time()+3600*24*30 will set the cookie to expire in 30 days. If this parameter is not set, the cookie will expire at the end of the session (when the browser closes). The example below will set the cookie to expire in 1 month from today.

$expiretime = time()+60*60*24*30;
setcookie("YourCookieName", "The data you would like to store inside the cookie!", $expiretime, path, domain);

 Path

The path part allows you to specify which part of the site will be able to access this cookie. If you set it for a specific directory then only files in that directory and subdirectories will be able to use that cookie. This is optional and without it, it will set it to / which will be usable by every file.

$expiretime = time()+60*60*24*30;
setcookie("YourCookieName", "The data you would like to store inside the cookie!", $expiretime, '/', domain);

Domain

The domain parameter is where you specify which domain is allowed to access this. Don't go thinking about trying to set it to something like facebook because it wont really help you haha. The reason this is here is because you can set it to be accessible by other subdomains etc. To just make it accessible to all subdomains of a specific domain then you can use this format .domain.tld however if you are in a shared hosting area and you share a domain like cazwebs.com then it is advisable for you to only set it to use that specific domain. You can see examples for both below:

All Sub Domains of the cazwebs.com domain

$expiretime = time()+60*60*24*30;
setcookie("YourCookieName", "The data you would like to store inside the cookie!", $expiretime, '/', ".demo.cazwebs.com");

Only demo.cazwebs.com

$expiretime = time()+60*60*24*30;
setcookie("YourCookieName", "The data you would like to store inside the cookie!", $expiretime, '/', "demo.cazwebs.com");

Reading a Cookie

Reading the contents of a cookie is far simpler than the above. To echo the contents of a cookie called YourCookieName all you would have to do is the following:

echo $_COOKIE['YourCookieName'];

If you wanted to see all cookies for that domain then you could do the following as remember, it is just an array like POST, GET and SESSIONS:

print_r($_COOKIE);

When doing this though, remember that this will only show cookies that havent expired, are available for this domain and are in the correct path.

Deleting a Cookie

To delete a cookie, you have to reset it but with a different expiry date. If you reset it and leave the expiry date blank then the browser should delete it when you leave the domain. However, I find this to be the best way:

$expiretime = time()+60*60*24*30;
setcookie("YourCookieName", "The data you would like to store inside the cookie!", 1, '/', "demo.cazwebs.com");

Playing with Cookies

Now its time to start playing with some cookies. We shall now create a VERY simple login form. As we don't have a database to play with, we shall store the login details in an array. This is not really recommended. In this, we are going to cover a lot of what we have previously learnt in other tutorials so make sure you have watched them first. We are also going to introduce something new: pseudocode. I will be using this just to help you get your head around the kind of things we will be needing to do throughout this tutorial and is very useful for planning. If you dont know already, pseudocode is an outline of a program, written in a form that can easily be converted into real programming statements. Here is a rough plan using pseudocode of what we will be doing.

PHP{
    Login Details() //ARRAY
    Check if login form has been submitted{
        Username and Password been submitted{
            Check if they are correct{
                Logged in. Create cookie
            }else{
                Show error()
            }
        }else{
            Show error()
    }    
    Check if there is a cookie{
        Check if details are correct{
            Logged in.
        }else{
            Delete Cookie
        }
    }
}
HTML{
    PHP{
        Check if Logged in{
            Show Welcome Message
        }else{
            Show Login Screen and any Errors.
        }
    }
}

The first thing we are going to work on is the html form. This is just so that we can log in.

<html>
    <head>
        <title>PHP For Beginners P11: Passing Variables P4 Cookies</title>
    </head>
    <body>
        <center>
            <h1>PHP For Beginners P11: Passing Variables P4 Cookies</h1>
            <form name="regForm" action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
                <table>
                    <tr>
                        <td>Username:</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>Password:</td>
                        <td><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><center><input type="submit" name="submit" value="Sign In" /></center></td>
                    </tr>
                </table>
            </form>
        </center>
    </body>
</html>

Now that we have the HTML taken care of, we can now start to work with the PHP. The PHP will need to go above the HTML. From the above, we can see that we need an array with the users login details inside it. This is just so we can check against these to make sure the user has entered the correct information. In real life, you would have this information stored in a database.

$credentialsArray=array(
    "Ben" => "Pass123",
    "James" => "CatsAreGreat",
    "admin" => "3piCZP@SSW0rdZ"
);

Now that we have the usernames and passwords stored in an array that can be easily accessible, we now need to check if the submit button has been entered. If you do not already know how the POST method works then you should check out this guide. After checking if the submit button has been pressed, we will go through and check to make sure if the username and password field have been entered as well. If they haven't then we shall save an error message to a variable and display it to the user later on.

if (isset($_POST['submit'])){
    //The submit button has been entered. Check if username and Password have been entered
    if(isset($_POST['username'])){
        //Username has been entered
        $username=$_POST['username'];
    }else{
        $message= "<p style='color:red;'>Please enter your Username</p>";
    }
    if(isset($_POST['password'])){
        //Username has been entered
        $password=$_POST['password'];
    }else{
        $message.= "<p style='color:red;'>Please enter your Password</p>";
    }

So far, in the php, we have dealt with the username and passwords and if they have been entered. Now, if they have been entered, we need to check if they are correct. The way we are going to do this is to see if the username has been set in the array. If it has then we can check if the value of the key (The password for this username) matches what the user has entered. If it is correct the the user has logged in. We then need to create them a cookie and set a variable to loggedin = true. If it is incorrect then we need to display that to the user. When we create a cookie, we will just save it as username with the value of the users username. Remember when you come to doing this in real life then you should not do it like this as it can be very easily hacked. We shall talk about this at a later date.

if(isset($credentialsArray[$username])){
        if($credentialsArray[$username] == $password){
            //Username and Password is correct.
            $expiretime = time()+60*60*24*30;
            setcookie("username", $username, $expiretime, '/', "demo.cazwebs.com");
            $loggedin=true;
        }
    }else{
            $message.= "<p style='color:red;'>Failed Login</p>";
    }

}

This is great, a user should now be able to log in. If however they have previously logged in with us before, we need to check if the cookie that user has is correct. We are going to first check if a cookie exists on their machine called cookie for this domain. If it does then we are going to check if this username is in our users list. If it does then we can log them in and show them a welcome message. If it doesn't then we are going to want to delete the cookie and show then the login screen as normal.

//Check if a cookie has already been set
if(isset($_COOKIE['username'])){
    //A Cookie with the name of username has been set. Check if that is in our user array. 
    $username=$_COOKIE['username'];
    if (isset($credentialsArray[$username])) {
        $loggedin=true;
    }else{
        $loggedin=false;
        setcookie("username", $username, 1 , '/', "demo.cazwebs.com");
    }
}

This is pretty much the end. We are just going to make a couple of the changes in the HTML. We are just going to get php to display the error messages to the user if they have any (login failed etc) and if they are logged in then we are going to show them the message of of Welcome.

<html>
    <head>
        <title>PHP For Beginners P10: Passing Variables P4 Cookies</title>
    </head>
    <body>
        <center>
            <h1>PHP For Beginners P10: Passing Variables P4 Cookies</h1>
        <? if(isset($message)){
            echo $message;
        }
        if($loggedin==true){
            echo "<p style='color:green;'>Welcome " . $username . "</p>";
        }else{
        ?>
            <form name="regForm" action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
                <table>
                    <tr>
                        <td>Username:</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>Password:</td>
                        <td><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><center><input type="submit" name="submit" value="Sign In" /></center></td>
                    </tr>
                </table>
            </form>
            <? }?>
        </center>
    </body>
</html>

We are done. The completed code can be seen below. Please also find a link to download the sourcecode.

<?
//Array of Users usernames and passwords. 
$credentialsArray=array(
    "Ben" => "Pass123",
    "James" => "CatsAreGreat",
    "admin" => "3piCZP@SSW0rdZ"
);
if (isset($_POST['submit'])){
    //The submit button has been entered. Check if username and Password have been entered
    if(isset($_POST['username'])){
        //Username has been entered 
        $username=$_POST['username'];
    }else{
        $message= "<p style='color:red;'>Please enter your Username</p>";
    }
    if(isset($_POST['password'])){
        //Username has been entered 
        $password=$_POST['password'];
    }else{
        $message.= "<p style='color:red;'>Please enter your Password</p>";
    }
    if(isset($credentialsArray[$username])){
        if($credentialsArray[$username] == $password){
            //Username and Password is correct.
            $expiretime = time()+60*60*24*30;
            setcookie("username", $username, $expiretime, '/', "demo.cazwebs.com");
            $loggedin=true;
        }
    }else{
            $message.= "<p style='color:red;'>Failed Login</p>";
    }

}

//Check if a cookie has already been set
if(isset($_COOKIE['username'])){
    //A Cookie with the name of username has been set. Check if that is in our user array. 
    $username=$_COOKIE['username'];
    if (isset($credentialsArray[$username])) {
        $loggedin=true;
    }else{
        $loggedin=false;
        setcookie("username", $username, 1 , '/', "demo.cazwebs.com");
    }
}
?>

<html>
    <head>
        <title>PHP For Beginners P10: Passing Variables P4 Cookies</title>
    </head>
    <body>
        <center>
            <h1>PHP For Beginners P10: Passing Variables P4 Cookies</h1>
        <? if(isset($message)){
            echo $message;
        }
        if($loggedin==true){
            echo "<p style='color:green;'>Welcome " . $username . "</p>";
        }else{
        ?>
            <form name="regForm" action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
                <table>
                    <tr>
                        <td>Username:</td>
                        <td><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td>Password:</td>
                        <td><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><center><input type="submit" name="submit" value="Sign In" /></center></td>
                    </tr>
                </table>
            </form>
            <? }?>
        </center>
    </body>
</html>

Attached Files







Also tagged with one or more of these keywords: PHP4Beginners