加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在AJAX请求中设置cookie?

发布时间:2020-12-13 16:38:47 所属栏目:PHP教程 来源:网络整理
导读:我正在使用jQuery AJAX调用 PHP来验证登录表单.在php中,我创建一个会话,如果他们检查’记住我’复选框,我想创建一个cookie.这里是PHP代码: ?phpinclude '../includes/connection.php';date_default_timezone_set('GMT');$name = $_POST['username'];$pass =
我正在使用jQuery AJAX调用 PHP来验证登录表单.在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;
 }



}


?>

会话已成功设置,但是该cookie并未设置.我已经尝试设置所有的值(域,路径等),但没有改变任何东西.有没有什么明显的我失踪?

以下几点建议:

>确保您指定了正确的过期日期格式
>在重定向页面上设置Cookie时,必须在调用头文件(“Location:….”)后设置该cookie;例如:

标题(‘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,’/’);

注意参数中的最后一个.

从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头一起发送的cookie.像其他标题一样,必须在脚本的任何输出之前发送cookie,这意味着在此之前不应该有任何html / code echo语句.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读