how to read php cookies with javascript correctly

好久不见. 提交于 2020-01-30 11:00:33

问题


consider this php and javascript code :

<?php $_COOKIE['test']='123'; ?>
<script>console.log(document.cookie);</script>

then what i see in console is : __utma=111872281.291759993.1444771465.1445374822.1445436904.4; __utmz=111872281.1444771465.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=8572f606897b1732c31a25dee29ca077

i want to use the value of $_COOKIE['test'] in javascript ... but this strange string is not useful for me . how can i do that ?


回答1:


<?php
$cookie_name = "test";
$cookie_value = "123";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

You need to write your php code like this

You can use this script If u can want particular cookie

<script>
function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

console.log(getCookie('test'));
<script>


来源:https://stackoverflow.com/questions/33724078/how-to-read-php-cookies-with-javascript-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!