簡體   English   中英

PHP Cookie不會設置

[英]PHP Cookie won't set

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

主頁內的代碼

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

我究竟做錯了什么?

提前致謝。

這只是一個猜測,但嘗試在你的setcookie中添加“/”作為第4個參數

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

添加:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM