Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create / retrieve / modify / delete a cookie

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 347
    Comment on it

    We use cookie to identify the identity of a user and make sure that the user is an authentic user when user traverses through different pages of an application or a website. Basically a cookie is a file in text format that is embedded by the server on the user's computer. Every time the server sends a response it also sends the cookie along with the response.There are some php functions that help us to create and retrieve cookie values.


    1- Creating Cookie : We create a cookie with the help of a php function setcookie().

    Syntax: setcookie(name, value, expire, path, domain, secure, httponly);

    In the setcookie funciton all the parameters are optional except name.
     

    Example (creating cookie):
    
    <?php
    
    $cookiename = "democookie"; // here a name is assigned to the variable
    
    $cookievalue = "Testing the demo cookie"; // here a value is assigned to the variable
    
    setcookie($cookiename, $cookievalue, time() + (86400 *10), "/"); // As 86400 seconds = 1 day
    
    ?>

    Now let us retrieve the cookie name and value:
     

    Example (retrieving cookie):
    
    <?php
    
    echo "Cookie name is :'" .$_COOKIE[$cookiename] ;
    
    echo <br>;
    
    echo "Cookie value is :'" . $_COOKIE[$cookievalue] ;
    
    }
    
    ?>

     

    3- Modifying a cookie : To modify the cookie we again use the same function setcookie() and change the value of the variable $cookiename and $cookievalue

     

    4- Deleting a cookie : For deleting a cookie we againg use the function setcookie and set the expiry date to 3 hour ago or as per the requirement.

    For example:
    
    <?php
    
    // setting the cookie expiry date to 3 hour ago
    
    setcookie("user", "", time() - 10800);
    
    ?>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: