gpt4 book ai didi

php - 在 AJAX 请求中设置 cookie?

转载 作者:行者123 更新时间:2023-12-03 00:16:27 25 4
gpt4 key购买 nike

我正在使用对 PHP 的 jQuery AJAX 调用来验证登录表单。在 php 中,我创建一个 session ,如果他们选中“记住我”复选框,我想创建一个 cookie。这是 PHP 代码:

<?php

include '../includes/connection.php';
date_default_timezone_set('GMT');

$name = $_POST['username'];
$pass = $_POST['password'];


$query = mysql_query("SELECT id, username, password FROM users WHERE username = '$name' LIMIT 1");

if(mysql_num_rows($query) == 0) {
echo 'error';
exit;
}

while($row = mysql_fetch_array($query)) {

if($row['username'] == $name && $row['password'] == $pass) {

session_start();
$_SESSION['username'] = $row['username'];
$_SESSION['usrID'] = $row['id'];
echo 'success';


if($_POST['remember']) {
setcookie('username', $row['username'], $exp);
setcookie('password', $row['password'], $exp);
setcookie('usrID', $row['id'], $exp);
}

} else {
echo 'error';
exit;
}



}


?>

session 设置成功,但 cookie 根本没有设置。我尝试设置所有值(域、路径等),但这没有改变任何内容。我有什么明显遗漏的东西吗?

最佳答案

这里有一些建议:

  • 确保您指定的日期过期格式正确
  • 在重定向的页面上设置 cookie 时,必须在调用 header('Location: ....'); 例如:

    header('位置:http://www.example.com/');
    setcookie('asite', $site, time()+60*60, '/', 'site.com');

  • 如果您有像 www.domain.com/path1/path2/ 这样的人工网址,那么您必须将 cookie 路径设置为/才能适用于所有路径,而不仅仅是当前路径。

    setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');

注意参数中的最后一个 /

来自 PHP 手册:

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

  • setcookie() 定义要与其余 HTTP header 一起发送的 cookie。与其他 header 一样,cookie 必须在脚本的任何输出之前发送,这意味着在此之前不应有 html/代码 echo 语句。

关于php - 在 AJAX 请求中设置 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com