php 在 AJAX 请求中设置 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3431906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:44:23  来源:igfitidea点击:

Setting a cookie in an AJAX request?

phpajaxcookiessession

提问by williamg

I'm validating a login form with jQuery AJAX call to PHP. In php, I create a session and if they checked the 'remember me' checkbox, I want to create a cookie. Here's the php code:

我正在使用对 PHP 的 jQuery AJAX 调用验证登录表单。在 php 中,我创建了一个会话,如果他们选中了“记住我”复选框,我想创建一个 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;
 }



}


?>

The session is set successfully, however the cookie is not set at all. I've tried setting all the values (domain, path, etc.) but that didn't change anything. Is there anything obvious I'm missing?

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

回答by Sarfraz

Here are few suggestions:

这里有一些建议:

  • Make sure that you are specifying the correct expiration format of date
  • When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....');eg:

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

  • If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.

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

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

    header('Location: 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, '/');

Notice the last /in the arguments.

注意/参数中的最后一个。

From PHP manual:

来自 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.

cookie 可用的服务器上的路径。如果设置为“/”,cookie 将在整个域中可用。如果设置为 '/foo/',则 cookie 将仅在 /foo/ 目录和域的所有子目录(例如 /foo/bar/ )中可用。默认值是设置 cookie 的当前目录。

  • setcookie()defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.
  • setcookie()定义一个 cookie 与其余的 HTTP 标头一起发送。像其他标题一样,cookie 必须在脚本的任何输出之前发送,这意味着在此之前不应该有 html/code echo 语句。

回答by David Kaneda

You won't be able to set the cookie server-side when using an AJAX call. Instead, wait until you get a successful response and set the cookie client side. To make it easier, you could use a jQuery plugin.

使用 AJAX 调用时,您将无法设置 cookie 服务器端。相反,等到您获得成功响应并设置 cookie 客户端。为方便起见,您可以使用 jQuery 插件