简体   繁体   中英

php setcookie not working as expected

I am learning PHP now. Any one can take a look at this and see why the cookie is not set and keep showing as empty?

<?php

    if ($_COOKIE["name"]) {
        echo "welcome back" . $_COOKIE['name'];
    }

    else {
        $fname = $_POST["fname"];
        $age = $_POST["age"];
        if ($fname) {
            echo "your name is ".$fname;
            setcookie("name", $fname, time()+6000);
            echo "cookie" . $_COOKIE['name'];
        }

        if ($age) {
            echo "your age is " . $age;
        }
    }

?>

<html>
<body>
<form action="index.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
<a href="info.php">info</a>
</body>
</html>

You probably get an headers already sent warning: You need to set the cookie before you send any output to the browser and you are doing an echo in the line before it.

So just make sure there is no output (empty lines, spaces, echoes, etc.) before you set the cookie.

Try

if ($fname) {
        setcookie("name", $fname, time()+6000);
        echo "your name is ".$fname;
        echo "cookie" . $_COOKIE['name'];
    }

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

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