简体   繁体   中英

Setting a cookie with php within JS gives me an error on line 29, returning a variable from PHP code?

I'm trying to experiment with getting and setting cookies with the PHP file below. I have a JavaScript function for checking to see (with is_set() ) if the cookie exists; if so, get the information with access() and delete the cookie (with delete_cookie() ) else write a cookie with write() .

The problem I'm getting is on this line(s),

SETTINGS[0] = <?php echo $HTTP_COOKIE_VARS["set_1"].?>;
SETTINGS[1] = <?php echo $HTTP_COOKIE_VARS["set_2"].?>;

with the error.

Parse error: syntax error, unexpected ';' in get_set_cookie.php on line 29

Here's the entire code, feel free to tell me if anything else is wrong.

<html>
<head>
<script language = "JavaScript">
var SETTINGS = new Array();

function check_cookie()
{
    if(if_set() == true)
    {
        alert("cookie found!");
        access();
        delete_cookie();
    }
    else
    {
        alert("set cookie");
        write();
    }
}
function is_set()
{
    if((true == <?php if( isset($_COOKIE["set_1"]))?>) && (true == <?php if( isset($_COOKIE["set_2"]))?>))
        return true;
    else
        return false;   
}
function access()
{
    SETTINGS[0] = <?php echo $HTTP_COOKIE_VARS["set_1"].?>;
    SETTINGS[1] = <?php echo $HTTP_COOKIE_VARS["set_2"].?>;

    var OUTPUT_TAG = document.getElementById("out_1");
    OUTPUT_TAG.innerHTML = SETTINGS[0]; 

    document.getElementById("out_2").innerHTML = SETTINGS[1];
}
function write()
{
    SETTINGS[0] = "nothing";
    SETTINGS[1] = "much";
    setcookie("set_1", "SETTINGS[0]", time()+31000000, "/","", 0);
    setcookie("set_2", "SETTINGS[1]", time()+31000000, "/", "",  0);
}
function delete_cookie()
{
    setcookie("set_1", "", time()-31000000, "/","", 0);
    setcookie("set_2", "", time()-31000000, "/", "",  0);
}
</script>
<style type = "text/css">
#out_1, #out_2
{
    color = black;  
}
body
{
    background-color: white;
}
</style>
</head>
<body onload "check_cookie()">
    <p id = "out_1"></p>
    <p id = "out_2"></p>
</body>
</html>

Replace

<?php echo $HTTP_COOKIE_VARS["set_1"].?>;

with

<?php echo $HTTP_COOKIE_VARS["set_1"];?>;
                                   //^----- Should be a semicolon !

Why you are putting a dot(.) before ?>. Removing it will solve the issue.

SETTINGS[0] = <?php echo $HTTP_COOKIE_VARS["set_1"]?>; 
SETTINGS[1] = <?php echo $HTTP_COOKIE_VARS["set_2"]?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM