PHP cookie code causing chaos
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 doe开发者_StackOverflow中文版s nothing.
PHP's setcookie
does it's thing via the headers, and unless you use output buffering, echo
ing before attempting setcookie
will 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
The problem is that you cannot set a cookie after data has been sent to the browser. If you echo text and then try to set the cookie, it won't work.
Try reversing the echo and the setcookie() and make sure that no text before it has been sent to the browser.
精彩评论