My script is fairly simple. When someone tries to login, PHP checks the form data against a MySQL database, set’s a cookie for the session, and refreshes the page. Now, I’ve pinpointed the cookie script to be causing chaos and completely stopping the thing from working. However, I don’t know why. The code I am using is this:
<?php
header('Content-type: text/javascript');
$erroron="false";
$id='false';
$con = mysql_connect("localhost","***","***");
if (!$con)
{
die('$("#connecterror").stop().hide().fadeIn(); ');
}
mysql_select_db("***", $con);
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
if( $row['username']==$_POST["user"]&&$row['password']==$_POST["pass"])
{
if($row['confirmed']==1){
$id=$row['id'];
}
else{
echo '$("#erroractivate").stop(false,true).hide().fadeIn(200);';
}
}
else if( $row['email']==$_POST["user"]&&$row['password']==$_POST["pass"])
{
if($row['confirmed']==1){
$id=$row['id'];
}
else{
echo '$("#erroractivate").stop(false,true).hide().fadeIn(200);';
}
}
else{
if($erroron=="false"){
$erroron="true";
echo '$("#error").stop(false,true).hide().fadeIn(200);';
}
}
}
if($id=='false'){
echo '$("#error").stop(false,true).hide().fadeIn(200);';
}
else{
echo '$("#page").text("You have logged in, redirecting...");$("body").css("cursor","wait");setTimeout("location.reload(true);",2000);';
setcookie("sessionid", $id,0,'/','profile.campatet.com',false,true);
}
mysql_close($con);
?>
Now, this the the part that is not working:
setcookie("sessionid", $id,0,'/','profile.campatet.com',false,true);
If I take that off, the script successfully refreshes the page, but because there is no cookie set, you can’t login. If I keep it on, it simply does nothing.
PHP’s
setcookiedoes it’s thing via the headers, and unless you use output buffering,echoing before attemptingsetcookiewill send the headers prematurely and prevent the cookie from being set.http://php.net/manual/en/function.setcookie.php
http://www.php.net/manual/en/intro.outcontrol.php