New to php and help regarding cookies

by 4 replies
5
I have a web application where i want to check whether cookie is there or not , if cookie is there i want to do something if its not there i would like to create new cookies.

How can i check whether cookies exist or not?
#programming #cookies #php
  • Lets say your cookie is called my_cookie:

    if(!isset($_COOKIE['my_cookie'])) {
    // Cookie is not set, set it
    setcookie('my_cookie', 'some value');
    }
    else {
    // Cookie exists, so something
    echo 'Im doing it';
    }
    • [1] reply
    • Don't forget to set an expiration time for the cookie, otherwise it will expire as soon as the user closes their browser.

      PHP Code:
      // Set cookie for 30 days (2592000 seconds)
      setcookie('my_cookie''some value'time() + 2592000); 
  • PHP Code:
    setcookie("cookie-name", -valuestrtotime'+30 days' ), "/"""""TRUE); 
    Cookie expire time is 30 days in this case.
  • <?php
    $expire=time();
    setcookie("user", "Alex Porter", $expire);
    ?>


    <?php
    if (isset($_COOKIE["user"]))
    echo "Welcome " . $_COOKIE["user"] . "!<br>";
    else
    echo "Welcome guest!<br>";
    ?>

Next Topics on Trending Feed