PHP Cookie不会设置

时间:2013-07-16 15:34:09

标签: php javascript jquery sql cookies

我可能正在做一些非常愚蠢的事情,但我无法弄明白。

主页内的代码

<script>
var pass = prompt("Enter pass:");

$.post(
"/php/sessions/set_session.php",
{ pass: pass },
function(result) {  
    if(result == "true")
    {
        window.location = "/Article_View/";
    }
    else
    {
        alert("Wrong password");    
    }
}
);
</script>

PHP代码

<?php
if($_POST["pass"] == "password")
{
    //Vars for connecting to database.
    $hostname = "secret";
    $username = "secret";
    $dbname = "secret";

    //Login vars
    $password = "secret";
    $usertable = "secret";

    //Connecting to database
    mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
    mysql_select_db($dbname);

    //set IDstring cookie for this sesh
    $expire = time()+60*60*24;//24hr cookie
    $IDstring = rand_string(10);
    setcookie("IDstring", $IDstring, $expire);

    //save IDstring to SQL for comparasent of cookie
    $query = "UPDATE {$usertable} SET IDstring='{$IDstring}'";
    $result = mysql_query($query);

    echo "true";
}
else
    echo "false";

//IDstring gen
function rand_string( $length ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  

    $size = strlen( $chars );
    for( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ rand( 0, $size - 1 ) ];
    }

    return $str;
}
?>

我可以看到它在phpmyadmin中设置了IDstring,但cookie根本没有设置。

我正在使用Chrome和Cookie已启用。它没有显示在资源中并且isset($ _ COOKIE [“IDstring”])返回false。

我做错了什么?

提前致谢。

2 个答案:

答案 0 :(得分:3)

这只是猜测,但尝试在你的setcookie中添加“/”作为第4个参数

setcookie("IDstring", $IDstring, $expire, "/");

答案 1 :(得分:0)

添加:

<?php
session_start();
...
?>