Setting a cookie with a $_GET function

Discussion in 'PHP' started by Seqqa, Sep 9, 2010.

  1. #1
    Hey Everyone,

    I want to set a cookie that expires in an hour that users URL vars to set it for example www.example.com/?a=whatever how can I get 'a' var from the URL and set it as a cookie and then on another page print the cookie?

    Thanks!
     
    Seqqa, Sep 9, 2010 IP
  2. Thorlax402

    Thorlax402 Member

    Messages:
    194
    Likes Received:
    2
    Best Answers:
    5
    Trophy Points:
    40
    #2
    You will need to get the value of the variable with $_GET['a']. After doing this you can simply use the php function setcookie() to set the cookie along with a name, value, and expiration. Here is the link to to documentation for that function: http://php.net/manual/en/function.setcookie.php.
     
    Thorlax402, Sep 9, 2010 IP
  3. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #3
    As described above it's pretty simple :

    To set the cookie:
    
    if($_GET['a']){
     //then the URL var exists so set the cookie
    
     //The URL param values could contain malicious values so remove html entities before storing/printing the value
     $var = htmlentities($_GET['a']);
    
     //set the cookie with 1 hr expiration
     setcookie("cookee",$var,time()+3600);
    }
    
    //Print cookie value
    echo $_COOKIE['cookee'];
    
    PHP:
    Is htmlentities good enough on its own for sanitizing the GET values? I'm not sure hopefully somebody could provide more info on this.
     
    wd_2k6, Sep 9, 2010 IP
    Seqqa likes this.
  4. Seqqa

    Seqqa Well-Known Member

    Messages:
    3,695
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    115
    #4
    Thanks for the code, it all makes sense now!
     
    Seqqa, Sep 9, 2010 IP
  5. SEOaaron

    SEOaaron Peon

    Messages:
    107
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Use POST rather than GET, it'll look tidier ;)
     
    SEOaaron, Sep 9, 2010 IP