未使用PHP setcookie函数设置的Cookie [英] Cookies not set using PHP setcookie function

查看:76
本文介绍了未使用PHP setcookie函数设置的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 setcookie php函数在浏览器中设置一些cookie.我尝试在PHP代码中设置cookie,然后使用 print_r($ _ COOKIE)对其进行检查.Cookie不会显示,但是如果我尝试在另一个文件中设置Cookie,将正确显示.

I'm using the setcookie php function to set some cookies in my browser. I try to set cookies in my php code and then I check it using print_r($_COOKIE). Cookies are not displayed, however if I try to set cookie in another file they will be displayed correctly.

if (isset($_POST['username']) && isset($_POST['password']))
{
    global $username,$password;
    $username = $_POST['username'];
    $password = sha1($_POST['password']);
    setcookie('username', $username, time()+3600); //cookie not set
    setcookie('password', $password, time()+3600); //cookie not set
    $database = connect_to_database($db_path);
    $result = $database->query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    while (true)
    {
        $response = $result->fetchArray(SQLITE3_ASSOC);
        if (!$response)
        {
            unset($_COOKIE['username']);
            unset($_COOKIE['password']);
            break;
        }
        if (($response['username'] == $username) && $response['password'] == $password)
        {
            header("location: ../index.php");
        }
    }

}

我希望设置cookie,但是使用 print_r($ _ COOKIE); 会返回 array()

I expected cookies to be set, but using print_r($_COOKIE); returns me array()

  • 在我的浏览器设置中允许使用cookie
  • $ _ POST ['username'] & $ _ POST ['password'] 通过另一页中的表单发送到此页
  • $ _ POST ['username'] & $ _ POST ['password'] 设置为真值.
  • Cookies are allowd in my browser settings
  • $_POST['username'] & $_POST['password'] sent to this page via form in another page
  • $_POST['username'] & $_POST['password'] are set with true value.

推荐答案

确保您拥有服务器和客户端都知道的域. echo $ _SERVER ['HTTP_HOST'] 应该告诉您浏览器具有完全相同的域.否则,浏览器将不接受cookie.

Make sure you have a domain that is known by both server and client. echo $_SERVER['HTTP_HOST'] should tell you the exact same domain that your browser has. If not, cookie will not be accepted by the browser.

确保您的服务器和客户端时间正确无误.浏览器将拒绝日期时间错误的Cookie.

Make sure your server and client time is perfectly correct. Browser will reject a cookie with a wrong datetime.

不要编写任何其他代码,而要做:

Do not write any other code and just do:

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day 
// expiration
echo date("H:i:s d.m.Y")."<br>";
echo $_SERVER['HTTP_HOST']."<br>";
var_dump($_COOKIE);
?>

并刷新页面两次.

也可以在以下位置查看手册: https://www.php.net/manual/en/features.cookies.php

Also check out manual at: https://www.php.net/manual/en/features.cookies.php

这篇关于未使用PHP setcookie函数设置的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆