Search code examples
phpcookiesterminalsetcookie

PHP script from command prompt - is it possible to set \ read cookies?


I have a simple php page, and I'm trying to run this php script is from the terminal console (ssh):

php /home/account/domains/domain.com/public_html/script.php

Now, I can run the script, the thing is, if I'm running the php script from the console, setting \ reading a cookie doesn't work, If I'm running the same page from the browser, everything work just fine (Read and write cookies..)

So my question is, can I run this script from the terminal (just like above), and make the cookies save somehow?

My php scrpit is simple:

setcookie("cookie", "cookie", time()+30);
if (!isset($_COOKIE["cookie"])){
echo "New Cookie is set!";
}else{
echo "The Cookie already set!";
}

Thank you very much for your help!


Solution

  • Cookies only exist in a browser. There's no browser involved when you run a script from the command line, so there's nowhere for those cookies to be stored.

    If you need to store data across calls to a command-line script, you will need to read and write it to a file. One simple way of doing this might be:

    // At the start of the script...
    $PERSIST = unserialize(file_get_contents("myscript.cache")) ?: array();
    
    // Read data from there...
    print $PERSIST["blah"];
    // Write some
    $PERSIST["foo"] = "stuff";
    
    // At the end of the script, save it back
    file_put_contents("myscript.cache", serialize($PERSIST));