1

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

主页面内的代码

<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。

我究竟做错了什么?

提前致谢。

4

2 回答 2

3

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

setcookie("IDstring", $IDstring, $expire, "/");
于 2013-07-16T15:54:12.390 回答
1

添加 :

<?php
session_start();
...
?>
于 2013-07-16T15:38:44.960 回答