Simple PHP Cookie

喜你入骨 提交于 2019-12-22 12:32:23

问题


I am experimenting with cookies and i am doing this quick example,

<html>
<head>
    <meta charset="UTF-8">
    <title>Cookies</title>
</head>
<body>
    <!-- Start of FORM -->
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
        Username: <input type="text" name="username"><br>
        <input type="submit" name="submit" value="Submit">
    </form>
    <!-- End of FORM -->
    <hr>
    <?php
    if (isset($_POST['username'] )) {
        setcookie('username', $_POST['username'], time() + 1000, '/');
        if(isset($_COOKIE['username'])){
            echo "Hello " . $_COOKIE['username'];
            unset($_COOKIE['username']);
        }
    }
    ?>
</body>

It works but i have to click the submit button twice for my message to display, why is that?


回答1:


From the PHP Docs..

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.

So whilst you clicked the button the second time, the actual load was in effect and you were able to see it(the cookie).



来源:https://stackoverflow.com/questions/23533456/simple-php-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!