PHP cookie code causing chaos - php

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 setcookie does it's thing via the headers, and unless you use output buffering, echoing 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.

Related

Unsetting PHP session variable doesnt display error message

I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.
I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...
This is part of my code flow...
<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
header('Location: index.php');
}
.
.
//in html body
<?php
if (isset($_SESSION['user_found'])){
if($_SESSION['user_found'] == 0){
?>
<div>
<p class = "bg-danger text-danger">Username Password Mismatch</p>
</div>
<?php
unset($_SESSION['user_found']);
}
}
?>
Now, if unset is removed..it works fine. If it is there, there is no display of error message.
Try not reloading the same page.. remove the header redirect.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
$_SESSION['admin_user'] = $result['id'];
header('Location: admin_user.php');
} else {
$_SESSION['user_found'] = 0;
//header('Location: index.php');
}
When I tried the your code, things seem to work fine. Something should be wrong with the code you've not mentioned here..
To troubleshoot the problem instead of
unset($_SESSION['user_found']);
try changing the value of the variable.. say
$_SESSION['user_found'] = -1;

php message using sessions

I am try to develop flash message using sessions in php
suppose on successfully delete query I am setting
$_SESSION["msg"]="record deleted successfully";
header("location:index.php");
and I have the following script on all pages which checks if msg variable is available it echo its value as below
if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
{
$msg=$_SESSION["msg"];
echo "<div class='msgbox'>".$msg."</div>";
unset($_SESSION['msg']); //I have issue with this line.
}
if I comment
unset($_SESSION['msg']);
message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.
You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.
Try adding exit; after header("location:index.php");.
Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1
In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
But this code probably will work as you want. Note that I have added exit after header line.
You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.
Another problem might be that you are doing more than one redirect.
You can simply set your session empty or null instead of unset it. Just do:
$_SESSION['msg']=NULL;
Or
$_SESSION['msg']="";

why i cant redirect to another page

what is the problem about this code?
it create session correctly but dont redirect me, there is no "echo" before "header".
if(isset($_POST['login'])){
include('../maincore/connect-db.php');
$username=$_POST['username'];
$password=$_POST['password'];
$result = mysql_query("SELECT * FROM supporter WHERE username='$username'")
or die(mysql_error());
$row = mysql_fetch_array($result);
$pass=$row['password'];
if($password==$pass && $password!=''){
$_SESSION['username']=$username;
$_SESSION['name']=$row['name'];
$_SESSION['family']=$row['family'];
$_SESSION['id']=$row['id'];
$_SESSION['type']=$row['type'];
header('location: works.php');
}else{
header('location: index.php');
}
}
If this is your real code, shouldn't you be using sha1 or some sort of irreversible hashing for your passwords? Just.. wondering..
Just tried your code, things are working fine on my end.. so you have to give us more info on your error logs
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message
The document headers should be send before the document content.
PHP executes at real time, when I request a page the page isn't evaluated and sent so when you write the documment starts to send teh documment and no more headers can be added to the transfer.
Your problem is than you echo something before the header.
Error examples:
<?php
session_start(); // Send the session id header.
echo "This is a rawr text"; // Print something to the document
header("location: index.php"); // And this line will throw a error cause you already writed in the document.
?>
Another error:
<?php
session_start();
?>
<body>
Inside of body
</body>
<?php
header("location: index.php"); // this will throw a error cause the text upside has been already sent.
?>
Solution:
Put your code (header() functions) before write in the document.

PhP Headers and output buffering

So... if you have a script that states something like so...
while($result = mysql_fetch_array($resource))
{
if($result['TITLE'] == $this->title)
{
header("LOCATION: profile.php?error=11");
}
echo 'testing';
}
//Create the database profile
$second_query = "INSERT INTO profiles(USER_ID, KEYWORDS, TITLE, INTRO) ";
$second_query .= "VALUES(".$this->userId.",'".serialize($this->keywords)."','".$this->title."','".$this->intro."')";
echo $second_query;
if($result = mysql_query($second_query))
{
if(isset($file))
{
$this->update_profile($this->files);
}
return true;
}else
{
return false;
}
and the first condition fails and sends the header back... If you don't return false after sending the header, does it continue running the script? I had an issue to where if the title was found in my database it would return the error, but it would continue running that script, thus inserting a duplicate title entry into my database.
So again... does a script continue executing even after you send a header? aka (in this case) a redirect?
If a location header is sent without an exit yes it continues to run script.
Valid:
header("Location: profile.php?error=11");
die(); // or exit();
Think about that header isn't executed by the PHP itself, it's executed by the browser, same thing when you apply a header("Content-Type: application/force-download"); it tells the browser that the following outputted block has to be downloaded.
So even if you set the header to another location, all code inside script, unless we exit, gets processed by PHP and then the browser gets the location and redirects.
Yes it will ,so exit your script after sending header
header("Location: profile.php?error=11");
exit;

PHP Session_start is hanging

Kind of a weird issue, ok here is my setup...
domain.com calls reads from an Iframe on sub.domain.com
sub.domain.com makes an ajax call to sub.domain.com/call.php
sub.domain.com returns ajax call to domain.com
AKA long-polling
Now, everything works perfectly when there is no session data (I close the browser and restart the page). However, once I reload the page and their is session data, call.php does a start_session() and hangs there.
I have tried almost everything and can't figure this out. I've tried destroying the session, unsetting all the session variables, modifying some ini settings, and nothing has worked.
Here is the code of call.php where the session data is...
session_start();
$sql = ("SELECT userid FROM status WHERE typing = '".mysql_real_escape_string($userid)."'");
$result = mysql_query($sql);
if ($result && mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$typing_id = $row['userid'];
if (!empty($typing_id)) {
if (isset($_SESSION['typing2'])) {
unset($_SESSION['typing2']);
}
} else {
$typing_id = "-1";
}
} else {
$typing_id = "-1";
if (isset($_SESSION['typing'])) {
unset($_SESSION['typing']);
}
}
if ($_SESSION['typing'] != $typing_id && !isset($_SESSION['typing2']) || $initialize == "1") {
$typing = array('typing_id' => $typing_id);
}
if ($typing_id == "-1") {
$_SESSION['typing2'] = "-1";
} else {
$_SESSION['typing'] = $typing_id;
}
Does anyone have any ideas? I was thinking it might have to do with the domain but I'm not sure.
Thanks!
I actually found out (after hours and hours of debugging and research) that the problem is being caused because the PHP session locks up. Then, when the new page loads, it won't work until the old session times out. A session_write_close() will fix it.
default session storage in php is cookie based. if you are using that you must set domain for your session cookie in php.ini
http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain

Categories