PHP, setcookie function not working

I have a code:

$user_cookie = hash("sha512",$username);
$salt1 = hash("sha512", rand() . rand() . rand());
setcookie("c_user", $user_cookie, time() + 12 * 60 * 60, "/");
setcookie("c_salt", $salt1, time() + 12 * 60 * 60, "/");

      

On localhost, it works fine, but not on the webserver. Why do not I understand? This code is included in the if and all other code from that if it works, but it doesn't. If I write echo $user_cookie."\n".$salt1;

I have these values!

+3


source to share


2 answers


According to the setcookie()

documentation

setcookie () defines a cookie that will be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before your script exits (this is a protocol limitation). This requires that you call this function before any exits, including tags as well as any spaces.

I had the same problem using cookies, the code was working fine on localhost but not working on the webserver, furthermore the headers are not working properly too. I started debugging by adding a temporary piece of code to my file:

header("Location: /test");

      

I found the below code is working correctly



header("Location: /test");
include("myfile.php");

      

and the other is not:

include("myfile.php");
header("Location: /test");

      

Eventually I realized that ?>

there is a space after there in myfile.php

How to fix the "Headers already sent" error in PHP

+2


source


This works for me to set a cookie within an hour from now for my local developer environment, which is running EasyPHP, and on the GoDaddy server for multiple domains:

setcookie($cookie, $value, time()+3600, '/', '127.0.0.1', true);

      



Try adding your domain (5th parameter /127.0.0.1) and I would recommend setting a safe boolean value too

+1


source







All Articles