phpjavascriptcookiesphpjs

Read and write cookies


I have a javascript file linked to a PHP page which has a value that needs be saved for when a form is submitted and the page is refreshed.

Is there a simple way to set cookies similar to the method in PHP.

setcookie("MovementDate", $MovementDate, time()+3600);  

Everything I have found is very complex and can't seem to get to work.

Also reading set cookies is currently an issue. From my searches I came up with this method however it's not working.

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}

}

var movement = readCookie(MovementDate);
document.write(movement);

Solution

  • If you're already comfortable with using PHP, you can use PHPjs:

    For setting, use the setcookie function.

    For reading, use the use the runkit_superglobals function. This will give you access to the the $_COOKIE superglobal using the exact same methods as PHP.

    Example:

    // Setting
    // setcookie uses seconds but the JS Date object returns milliseconds,
    // so we need to divide by 1000
    setcookie("foo", "bar", (new Date().getTime() / 1000) + 3600);
    
    // Reading
    runkit_superglobals();    
    alert($_COOKIE["foo"]); // alerts "bar"