2

I have the 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 on webserver doesn't work. I can't understand, why? This code is included in if and all other code from this if works but this-no. If I write echo $user_cookie."\n".$salt1; I have these values!

Shehary
  • 9,926
  • 10
  • 42
  • 71
Nicolae Casîr
  • 892
  • 1
  • 10
  • 18

2 Answers2

1

According to setcookie() documentation

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.

I had the same problem using cookies, the code was working fine on the localhost but doesn't work on the webserver, beside that headers doesn't work properly too. I started debuging by adding a temporary piece of code to my file:

header("Location: /test");

I found that the code below works properly

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

while the other one doesn't :

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

After all, I figured out that there was a space after ?> in myfile.php

How to fix "Headers already sent" error in PHP

Community
  • 1
  • 1
0

This works for me to set a cookie for an hour from now for my local dev environment running EasyPHP and on a GoDaddy hosted server for several domains:

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

Try adding your domain (the 5th parameter/127.0.0.1) and I would recommend setting the secure boolean to true as well

isuPatches
  • 6,384
  • 2
  • 22
  • 30