New to php and help regarding cookies

4 replies
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?
#cookies #php
  • Profile picture of the author Paul Moss
    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';
    }
    {{ DiscussionBoard.errors[8254352].message }}
    • Profile picture of the author Brandon Tanner
      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); 
      Signature

      {{ DiscussionBoard.errors[8254444].message }}
  • Profile picture of the author Rennell Garrett
    PHP Code:
    setcookie("cookie-name", -valuestrtotime'+30 days' ), "/"""""TRUE); 
    Cookie expire time is 30 days in this case.
    {{ DiscussionBoard.errors[8256793].message }}
  • Profile picture of the author octalsoftware
    <?php
    $expire=time();
    setcookie("user", "Alex Porter", $expire);
    ?>


    <?php
    if (isset($_COOKIE["user"]))
    echo "Welcome " . $_COOKIE["user"] . "!<br>";
    else
    echo "Welcome guest!<br>";
    ?>
    {{ DiscussionBoard.errors[8271035].message }}

Trending Topics