Ismael Quirantes Ismael Quirantes - 11 months ago 212
Ajax Question

Cookies are not setting with setcookie();

I've a server where I test everything before setting it in my main server. The issue appears when i'm setting a cookie with setcookie();

I'm using a cookie to set a session with ajax, the code is this:

require '../init.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
$newhash = createHash();

//LOGIN STUFF
if(strtolower($user) == strtolower($userA['user']))
{
if($pass == $userA['pass'])
{
$expiration = ( time() + ( 24 * 60 * 60 * 365) );
setcookie('session', $newhash, $expiration, '/');
$userAdd = MYSQL_::Bits("INSERT INTO users_sessions (hash,userid) VALUES ('$newhash','$userAID')");
//LOGIN STUFF
}
else
{
$datos = array('response' => 'fail','reason' => 'pass');
}
}
else
{
$datos = array('response' => 'fail','reason' => 'user');
}
header('Content-Type: application/json');
echo json_encode($datos, JSON_FORCE_OBJECT);


This code works perfectly on localhost, but when I put it in my main host it doesn't. I've been reading all this related posts on stackoverflow and no one has the solution, it says that there can't be nothing before the cookie but it'd be impossible to set the cookie with nothing before it. I wish someone had the answer :-(

Answer Source

You have output somewhere in init.php or any files init includes.
The output can be direct, as in a echo.
Or a space before the PHP tag or I think even an error/notice created by PHP.
As I wrote in comments find out where your output is, we can't help you with that.

You can as mentioned move then setcookie around in your code and see where it works and where it doesn't work.
When it stops working you have found the line that creates an output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download