Setcookie () doesn't work on my site, same works on phpfiddle & w3schools

Can't set cookie with php 'setcookie' on my website.

Its the basic code I got from w3schools. It works on w3schools (example works in my browser), also works on phpfiddle, but just won't work on my site no matter how many times I update. Here is the exact code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$cookie_name = "user3";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value); // 86400 = 1 day


if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

      

This exact code works when I put it in the phpfiddle. But doesn't work on my site.

Also, when I try to set a cookie with JavaScript - it works great.

+3


source to share


2 answers


try to put the code

$cookie_name = "user3";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value);

      



above html content ie

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      

+1


source


This helps to understand the underlying mechanism for the cookies set here. Cookies are set only in the header of the request response (except for using javascript cookie setting methods, that is). A setcookie()

call, in fac, t is just a convenience function that abstracts the programmer from having to manually set the cookie-related response headers.

Since headers can ONLY be sent before any actual HTTP response content is sent, you MUST make any calls setcookie()

(like any calls header()

) before any response body is sent.



In your case, you are sending multiple lines of HTML before the call setcookie()

, meaning the header containing the cookie will never be sent as it is already too late in the response loop. You need to carry this code before any exit you make to the browser.

+1


source







All Articles