Cookie FAQs in PHP

  • What is a Cookie?
    A cookie is often used to identify a user. 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.


  • How to Create a Cookie?
    setcookie(name, value, expire, path, domain);
    Example -
    setcookie("user", "Alex Porter", time()+3600);


  • How to Retrieve a Cookie Value?
    The PHP $_COOKIE variable is used to retrieve a cookie value.
    Example -
    // Print a cookie
    echo $_COOKIE["user"];
    // A way to view all cookies


    How to Delete a Cookie?
    When deleting a cookie you should assure that the expiration date is in the past.
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);


    Example program Checking for Cookie Support from PHP:

    < ? php
           setcookie("testcookie", "test value");
           header("Location: {$_SERVER["PHP_SELF"]}?testcookie=1");
             echo "You have cookies enabled";
             echo "You do not support cookies!";
      ? >

  • What? looking for output? why don’t you try the output? Execute the above program and comment us your output. Correct output is appreciated.

    0/Post a reply/Replies

    Previous Post Next Post