简体   繁体   中英

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. 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. 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). 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)

    <?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

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'. 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:

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

After setting the cookie you should reload your page, you can use 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

See the setcookie documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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