PHP - Setcookie(); Not Working

PHP – setcookie() not working

PHP superglobals are populated at script start-up time, and then are NOT modified or touched by PHP again for the life of the script. That means $_COOKIE represents the cookies that were sent to the server in the http request that fired up the script. It will NOT show any cookies you've added/changed/deleted during the life of the script. Those changes will only show up on the NEXT request.

The only exception to this is $_SESSION, which is populated when you call session_start().

If you need those values to be in $_COOKIE immediately, you'll have to add them manually, e.g.

setcookie('cookie', $value, ....);
$_COOKIE['cookie'] = $value;

PHP - setcookie(); not working

You have to set cookies before any headers are sent out.

From the manual:

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.

This means you will need to look into output buffering if you wish to use this code as is.

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

Depending on the contents of global.php, this might work for you. All I did was remove any output before setcookie() is called. If global.php contains any whitespace or HTML output in it this won't work:

<?php 
include "global.php";

if(isset($_POST["email"])){
$email = $_POST["email"];
$password = sha1($_POST["password"]);
$check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'");
$check = mysqli_num_rows($check);
if($check == 1){
setcookie("PeopleHub", $email, 0, '/');
echo "We logged you in!";
}
else {
echo "We couldn't log you in!";
}
}
?>
<h2>Login</h2>
<?php
echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. ";
?>
<br>
<br>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
Email <input name="email" placeholder="Email Address" required="" type="text"><br>
Password <input name="password" placeholder="Password" required="" type="password"><br>
<input type="reset" value="Start Over">
<input type="submit" value="Login">
</form>

setcookie() function not working

You may be calling this function after headers were already sent:

try this and see if you get an exception:

function connexionOK() {
$cookieName = "CookieCo";
$cookieValue = "true";
if(headers_sent()){
throw new Exception('Cannot set cookie, headers already sent');
}else{
$isSent = setcookie($cookieName, $cookieValue, time() + 3600, "/");
if($isSent){
echo '<script type="text/javascript">';
echo "alert('Cookie set');";
echo "</script>";
}else{
echo '<script type="text/javascript">';
echo "alert('Cookie not set');";
echo "</script>";
}
}
}

connexionOK();

If so, you will need to refactor and make sure you setcookie before headers are sent.

EDIT: The above code was included to more clearly illustrate the problem - it is poorly written and includes a lot of redundancy as calling set setCookie while headers are sent will already throw an exception and probably terminate execution. If this is NOT the case, you will need to add checks and handle them accordingly.

Cookies not set using PHP setcookie function

Make sure you have a domain that is known by both server and client. echo $_SERVER['HTTP_HOST'] should tell you the exact same domain that your browser has. If not, cookie will not be accepted by the browser.

Make sure your server and client time is perfectly correct. Browser will reject a cookie with a wrong datetime.

Do not write any other code and just do:

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
// expiration
echo date("H:i:s d.m.Y")."<br>";
echo $_SERVER['HTTP_HOST']."<br>";
var_dump($_COOKIE);
?>

and refresh the page twice.

Also check out manual at: https://www.php.net/manual/en/features.cookies.php

PHP's setcookie() function is not working. What's wrong?


I know the cookie expiry date is set in the future. I know the expiry
date is NOT larger than PHP's integer max-size PHP Integer maximum
value is about 32 bits, mine is no more than 5 characters

Uh, shouldn't the expiry time of a cookie be the number of seconds since epoch? A 5 digit expiry date would be early January 2nd, 1970, so I don't think it's possible that your expiry date is both five characters or less, and also in the future.

http://php.net/manual/en/function.setcookie.php:

This is a Unix timestamp so is in number of seconds since the epoch.
In other words, you'll most likely set this with the time() function
plus the number of seconds before you want it to expire

<?php
setcookie("hiworld", "true", time()+300);
?>
Hi, world!


curl -v danf.us/t.php
* Adding handle: conn: 0x7ff05180d000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7ff05180d000) send_pipe: 1, recv_pipe: 0
* About to connect() to danf.us port 80 (#0)
* Trying 66.191.143.117...
* Connected to danf.us (66.191.143.117) port 80 (#0)
> GET /t.php HTTP/1.1
> User-Agent: curl/7.30.0
> Host: danf.us
> Accept: */*
>
< HTTP/1.1 200 OK
* Server nginx/1.0.10 is not blacklisted
< Server: nginx/1.0.10
< Date: Fri, 02 Jan 2015 22:31:19 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=20
< X-Powered-By: PHP/5.3.13-pl0-gentoo
< Set-Cookie: hiworld=true; expires=Fri, 02-Jan-2015 22:36:19 GMT
<
Hi, world!
* Connection #0 to host danf.us left intact

PHP 5.5 setcookie localhost not working

Try this, sets cookie

$time=time();
setcookie("test", "value", time()+86400);

The time can be adjusted it's set for one day before it expires.

To read the cookie

$varname = $_COOKIE["test"]; 
echo $varname;

It should echo out value since that is the example data your setting in cookie.

You can also use the same name for setcookie to override your existing value



Related Topics



Leave a reply



Submit