简体   繁体   English

在PHP中设置/检查cookie的问题

[英]Problem setting/checking cookie in PHP

I have a small basic website with certain pages users can only view when they are logged in. There's only 1 username and password because the site is for just a few people and security isnt a major issue. 我有一个小型的基本网站,用户只能在登录时查看某些页面。只有1个用户名和密码,因为该网站仅供少数人使用,安全性不是主要问题。 Anyway, when the user types in the correct Username and password and submits, a cookie is set in the code and the page is reloaded. 无论如何,当用户输入正确的用户名和密码并提交时,会在代码中设置cookie并重新加载页面。 But it still shows the content as if the user werent logged in. When I press the sumbit button again or just click to another page, the content is shown correctly (more items in the navigation bar). 但它仍然显示内容,好像用户没有登录。当我再次按下sumbit按钮或只是单击到另一个页面时,内容显示正确(导航栏中的更多项目)。 I cant find out why it wont show the items the first time. 我无法找出为什么它不会第一次显示这些项目。

The top of the login page: 登录页面的顶部:

    if (isset($_POST['reg'])){
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        logon();
    }
} else {
   show_form();
}

The content of the page (function show_form) 页面内容(函数show_form)

    <?php
    if( isset($_COOKIE['logedon'])){
        echo '<p>You are now logged on</p>';
        }
    else{
          //shows form containing: <input type="hidden" name="reg" value="1"/>
    }
?>

and finally the logon() function 最后是logon()函数

function logon(){
$expire= 60 * 60 * 24 * 10000 + time(); 
setcookie('logedon', true, $expire); 
show_form();
}

So the cookie is set, the show_form function is called but still shows the form instead of the echo 'you are now logged on'. 因此设置了cookie,show_form函数被调用但仍显示表单而不是echo'你现在登录'。 When I switch page or hit the submit button again, the echo is displayed. 当我再次切换页面或点击提交按钮时,会显示回显。 Why doesnt it do that the first time? 为什么它第一次不这样做?

Please help! 请帮忙!

The setcookie docs say: setcookie文档说:

Cookies will not become visible until the next loading of a page that the cookie should be visible for. 在下一次加载可以看到cookie的页面之前,Cookie不会显示。 To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. 要测试cookie是否已成功设置,请在cookie过期前检查下一个加载页面上的cookie。 Expire time is set via the expire parameter. 过期时间通过expire参数设置。 A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);. 调试cookie存在的一种好方法是简单地调用print_r($ _ COOKIE);.

After setting the cookie you should reload your page, you can use header('location:http://someurl');die(); 设置完cookie后你应该重新加载你的页面,你可以使用header('location:http://someurl');die();

Just manually refresh the page once the log in is done using the header function. 只需使用标题功能完成登录后手动刷新页面。 Once the cookie is set, it can be accessed only in the next page reload 设置cookie后,只能在下一页重新加载时访问它

See the setcookie documentation . 请参阅setcookie文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM