• 5th November 2009 - By admin

    A cookie is a small file that the server embeds on the user’s computer. This data is sent and recieved with each browser that is used to view a page using cookies.

    To create a cookie in PHP use the setcookie() function. Here is its syntax:

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

    So if you want to create a cookie for someone’s status that will last one day, the code would look something like this:

    // name = status
    // expire = current timestamp plus 24 hours
    // path = current path "/"
    setcookie("status","user status here",time()+(3600*24),"/");

    So let’s say we want to create a cookie for every user that logs in and have it last for 12 hours. We need to run a login form and validate the login details to match someone on our database, and then create the cookies and set them to a specific time interval. Let’s make a function for this on function.php:

    function.php

    <?php
    // function.php

    function run_login_form($username,$password){
    $username = trim(addslashes($username));
    $password = md5(trim($password));

    $sql = mysql_query("SELECT userid FROM users WHERE username = ‘$username‘ AND password = ‘$password‘ LIMIT 1");
    if(mysql_num_rows($sql) > 0){
    $row = mysql_fetch_assoc($sql);
    // User found, now let’s create the cookies for the user!
    setcookie("userid",$row["userid"],time()+(3600*12),"/");
    setcookie("username",$username,time()+(3600*12),"/");
    return true;
    } else {
    return false;
    }

    }
    ?>

    Now if you have a simple form with two inputs, one for username and password, you can send these to a login page which will run the above function to validate and check the login. We’ll put this form on our index.php:

    index.php

    <html>
    <head>
    <title>PHP Login / Logout</title>
    </head>
    <body>
    <form action="login.php" method="post">
    Username: <input type="text" name="username" maxlength="25" /><br/>
    Password: <input type="password" name="password" maxlength="40" /><br/>
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>

    Now on login.php we include that function and run it with the submitted username and password.

    login.php

    <?php
    // login.php

    include("function.php");

    if($_POST["submit"]){

    $login = run_login_form($_POST["username"],$_POST["password"]);
    if($login){
    echo "Login successful! Welcome back!";
    } else {
    echo "Login unsuccessful! Please try again.";
    }

    }

    ?>

    Now we’ve made the user logged in. Basically we checked the mysql database for a user with those login details and upon finding a match, we created two cookies for that user. One being their userid (an ID we keep in our database for each user) and the other being their username.

    So what if the user wants to log out? This is very easy when dealing with simply erasing the cookies we made. We place the following code on our index.php page.

    <?php
    // index.php continued

    if($_GET["do"] == "logout"){

    if($_COOKIE["userid"] && $_COOKIE["username"]){
    // user is logged in, now log them out!

    // set the cookies to a time less than the current timestamp
    setcookie("userid","",time()-3600,"/");
    setcookie("username","",time()-3600,"/");
    }

    }

    ?>

    Now when the user visits index.php?do=logout it will run this logout code. If the cookies are found, it erases them and they will be treated as a guest based on how your script treats users without these cookies. This way we can check each user on every page they visit for these cookies to tell if they are a registered and logged in user or a guest.

  • 23 Responses to “PHP Cookies with Login – setcookie()”

    • [...] Read the rest here: PHP Cookies with Login – setcookie() [...]

    • Hospedagem TI Facil on June 7, 2010

      Good morning, thanks for the post? Is your blog a free theme or custom? I am intrigued by your blog. Is it possible to include this post on one of my blogs?, i will of course link to this page. Many Thanks

    • Kelsi Janosko on June 11, 2010

      Wonderful article which has received me considering concerning the prospective of the idea. Actually actually remarkable.

    • Epic Traffic System Review on June 12, 2010

      Thanks because of this! I’ve been searching all more than the web for that data.

    • I am quite interesting in this topic hope you will elaborate more on it in future posts

    • Amit khare on June 22, 2010

      Awesome tutes.. :-)

    • Kathleen Santago on June 29, 2010

      Hello This is a great blog keep your good work and thank you for hvar in with me So nice to hear frome you.Thanks!

    • compare lcd tv on July 2, 2010

      Thanks for this video…I have been brain storming for something just like this and thanks to you I have what I was looking for and not all those spam looking links that make you want to click them just to see what they lead too…my pet peave.

    • claim insurance on July 3, 2010

      This is indeed a fantastic resource. Thank you for making this publicly available.

    • Regena Holub on July 10, 2010

      Thanks-a-mundo for the blog article.Really thank you! Will read on…

    • Neal Bowling on July 10, 2010

      I feel the information pointed out in the subject is actually very useful. I have been participating in a research on the issue and your writings just covered a great deal of concerns I had. I’m writing an essay and term paper for my English course and recently following a bunch of blogs and forums to study.

    • Chris Dunny on July 10, 2010

      When I just recently found your blog and have been following along, I was thinking I would write my first comment. I don’t know just what to say apart from I really enjoyed reading. Very good writings. I am going to continue coming to this website on a regular basis.

    • Amie on July 10, 2010

      This is a best place for such kind of articles, your website is a inspiration for me. i got so very much benefits and great results after visiting here and the grace is increasing day by day in your posts. The above information is extremly essential.

    • Amiee Ammirato on July 11, 2010

      I was quite pleased to find this web site.I wanted to thank you for this fantastic study I definitely enjoying each and every little bit of it and I have you bookmarked to check out new stuff you post.

    • bad credit student loans on July 15, 2010

      Quite interesting piece of information. Many Thanks!

    • kampanie AdWords on July 26, 2010

      Super text, I will add this blog to my favorites.

    • sleeping bags on July 28, 2010

      I found your web log from AOL which is outstanding. Thank you for sharing such a good helpful article.

    • quality backlinks on August 2, 2010

      I’m impressed! Really informative blog post here my friend. I just wanted to comment & say keep up the quality work. I’ve bookmarked your blog just now and I’ll be back to read more in the future my friend! Also nice colors on the layout, it’s really easy on the eyes.

    • Rosendo Ermatinger on August 12, 2010

      I fairly accept a person’s mindset, this blog is basically great, superior as well, refueling.

    • Kindermode on August 16, 2010

      Hi there, I can’t are aware of how to include your internet site in my rss reader. Can you Allow me, please

    • Samira Lundholm on August 17, 2010

      Hi administrator I wallow in w/ ur content . may i copy this advice as my educate test ? thanks

    • Eldon Foute on August 22, 2010

      Hello dude,i like this A New blog very much. attain u allow suggestion being my blog? thanks for A New attention

    • Elliott Lofstrom on August 30, 2010

      Hello dude,i like Your New site very a lot. attain u allow suggestion being my blog? thanks being Ones New attention

    Leave a Reply

    Powered by WP Hashcash


bgallz.org is for training purposes only. Its content is to be used at the risk of the user. We do not guaruntee its accuracy.