Jump to content

[SOLVED] Can't set cookie for login with "remember me" - gets header warning


young_nickodemus

Recommended Posts

Hi All,

 

I'm really hoping someone can help me with what i reckon must be an easy to fix prob...

 

I'm trying to do a login with remember me function. The log in form sits on the index.php page. On entering the correct username/password, the page redirects to that users homepage.php. If the uer subsequently tries to return to index.php the browser immediately redirects to the users homepage. (hope that makes sense).

 

So far, all of that works. Also, if the user enters the wrong username/password it just puts the error mesasage "wrong username or password" under the form and gets the user to try again.

 

The prob is that when the user enters the correct username/password AND clicks the remember me check box, it still logs the user in, but it gives the error "cannot modify header information. headers already sent by (output already started..." . But it then redirects the page to homepage.php and all works fine!! The only thing that thing that doesn't work is that it doesn't remember the user after the browser has closed....ie the cookie isn't getting set i don't think...

 

FYI - if i comment out the setcookie() bits, i don't get the warning...

 

ANy ideas would be amazing...I'm v new to php.

 

Code below:

index.php

<?php
session_start();
include("connect.php");
include("getbutton.php");
function confirmUser($username, $password){
   global $conn;
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
$username = addslashes($username);
   }

   /* Verify that user is in database */
   $q = "select password from users where username = '$username'";
   $result = mysql_query($q);
   if(!$result || (mysql_numrows($result) < 1)){
      return 1; //Indicates username failure
   }

   /* Retrieve password from result, strip slashes */
   $dbarray = mysql_fetch_array($result);
   $dbarray['password']  = stripslashes($dbarray['password']);
   $password = stripslashes($password);

   /* Validate that password is correct */
   if($password == $dbarray['password']){
      return 0; //usernmae/password correct
   }
   else{
      return 2; //password failure
   }
}

// Function to see if cookie is set, then checks the username with the password
function loggedIn(){
   if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
      $_SESSION['username'] = $_COOKIE['cookname'];
      $_SESSION['password'] = $_COOKIE['cookpass'];
   }

   if(isset($_SESSION['username']) && isset($_SESSION['password'])){
   
      if(confirmUser($_SESSION['username'], $_SESSION['password']) != 0){
         unset($_SESSION['username']);
         unset($_SESSION['password']);
	 // username/password wrong
         return false;
      }
  // user logged in and correct username/password
      return true;
   }
   // no cookies set
   else{
      return false;
   }
}

$logged_in = loggedIn();
// check if logged
if($logged_in){
// if logged on already redirect to homepage
   	header("Location: http://www.website.net/homepage.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    	<div id="loginDiv">
		<?
				include ("loginform.php");
		?>
</div>
</body>
</html>

 

loginform.php

<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="0">
<tr><td style="color:#999; font-weight:bold; text-align:right;">Username:</td><td colspan="2"><input type="text" name="userName" height="10" size="15" maxlength="30"></td></tr>
<tr><td style="color:#999; font-weight:bold; text-align:right;">Password:</td><td colspan="2"><input type="password" name="userPass" height="10"  size="15" maxlength="30"></td></tr>
<tr><td align="right" style="color:#999; font-weight:bold; text-align:rigt;">Remember:</td><td align="left" style="padding-left:0"><input style="margin-left:0" type="checkbox" name="remember"></td><td align="right" style="padding-right:5px"><input class="textassubmitbutton" style="text-align:right" type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>
<?php
if(isset($_POST['sublogin'])){
session_start();
include_once("connect.php");
$username = $_POST['userName'];
$password = md5($_POST['userPass']);

$ress = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$rows = mysql_fetch_array($ress);

if(($rows["username"]==$username)&&($rows["password"]==$password)) {
	$_SESSION['username']=$username;
	$_SESSION['password']=$password;
        // THIS IS THE BIT THAT APPEARS TO BE CAUSING THE PROBLEM
	if(isset($_POST['remember'])){
		setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
		setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
	}
	echo "<meta http-equiv=\"refresh\" content=\"0;url=http://www.website.net/homepage.php\" />";
	return;

} else {
	echo "<br /><br /><br /><br /><br /><font style=\"color:#F00; margin-left:20px\">Wrong username or password</font>";
}
}

?>

 

I'm getting desperate...please, any help would be AMAZING!!!

 

Thanks,

 

Nick

Link to comment
Share on other sites

Hi young_nickodemus,

 

This error is occuring because you are outputting HTML infomration before the PHP code.

 

Put your PHP code above your HTML and try again - the problem should then be fixed!

 

Hope this helps.

 

Hi Bricktop,

 

Thanks for the reply.

 

I swapped it around in loginform.php, but it didn't help the error still appears only when i try to set the cookie for remember me.

 

If the user doesn't click "remember me" no error appears and it all works fine with the redirect and stuff.... :'(

 

Any other ideas...

Link to comment
Share on other sites

Hi young_nickodemus,

 

Basically if a single characters (including a whitespace) gets sent before the cookie gets set, and error will occur.

 

Check for any extra whitespaces after the ; at the end of each line and try again.

 

Also, have a read of the useful article on headers here http://www.phpfreaks.com/forums/index.php/topic,37442.0.html

 

Hope this helps.

Link to comment
Share on other sites

Hi young_nickodemus,

 

Basically if a single characters (including a whitespace) gets sent before the cookie gets set, and error will occur.

 

Check for any extra whitespaces after the ; at the end of each line and try again.

 

Also, have a read of the useful article on headers here http://www.phpfreaks.com/forums/index.php/topic,37442.0.html

 

Hope this helps.

 

Thanks again Bricktop.

 

Sorry...i had read that article before i posted, but couldn't see how i could change my code, if i needed to.

 

As you suggested, i went back through my loginform.php file and checked for any whitespace that might be output, but can't find any. I even deleted every tab, space, etc in the file just to make sure. the file now looks like this:

<?php
if(isset($_POST['sublogin'])){
session_start();
include_once("connect.php");
$username = $_POST['userName'];
$password = md5($_POST['userPass']);
$ress=mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$rows=mysql_fetch_array($ress);
if(($rows["username"]==$username)&&($rows["password"]==$password)){
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if(isset($_POST['remember'])){
setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
}
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://www.website.php\" />";
return;
}else{
echo "<font style=\"color:#F00; margin-left:20px\">Wrong username or password</font>";
}
}
?>
<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="0">
<tr><td style="color:#999; font-weight:bold; text-align:right;">Username:</td><td colspan="2"><input type="text" name="userName" height="10" size="15" maxlength="30"></td></tr>
<tr><td style="color:#999; font-weight:bold; text-align:right;">Password:</td><td colspan="2"><input type="password" name="userPass" height="10"  size="15" maxlength="30"></td></tr>
<tr><td align="right" style="color:#999; font-weight:bold; text-align:rigt;">Remember:</td><td align="left" style="padding-left:0"><input style="margin-left:0" type="checkbox" name="remember"></td><td align="right" style="padding-right:5px"><input class="textassubmitbutton" style="text-align:right" type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>

 

The problem is that the form is in the middle of an HTML file, but when the form submits with the wrong username/password, i want the warning ("wrong username/password") to appear below the form itself without any other change to the page.

 

The only way i've been able to get the page to work with remember me, is to let the page change to one with just a warning on it. But then the user has to go back to the login page or index.php or something to try again. This isn't really desirable.

 

I call the loginform.php with

include ("loginform.php");

 

where i want the form to appear in the index.php page...could this be a problem? I don't know how else i can do this...

 

Really appreciate you trying to help.

Link to comment
Share on other sites

this looks fine to me

<?php
session_start();
#include("connect.php");
#include("getbutton.php");
function confirmUser($username, $password){
   global $conn;
   /* Add slashes if necessary (for query) */
   if(!get_magic_quotes_gpc()) {
   $username = addslashes($username);
   }

   /* Verify that user is in database */
   $q = "select password from users where username = '$username'";
   $result = mysql_query($q);
   if(!$result || (mysql_numrows($result) < 1)){
      return 1; //Indicates username failure
   }

   /* Retrieve password from result, strip slashes */
   $dbarray = mysql_fetch_array($result);
   $dbarray['password']  = stripslashes($dbarray['password']);
   $password = stripslashes($password);

   /* Validate that password is correct */
   if($password == $dbarray['password']){
      return 0; //usernmae/password correct
   }
   else{
      return 2; //password failure
   }
}

// Function to see if cookie is set, then checks the username with the password
function loggedIn(){
   if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){
      $_SESSION['username'] = $_COOKIE['cookname'];
      $_SESSION['password'] = $_COOKIE['cookpass'];
   }

   if(isset($_SESSION['username']) && isset($_SESSION['password'])){
      
      if(confirmUser($_SESSION['username'], $_SESSION['password']) != 0){
         unset($_SESSION['username']);
         unset($_SESSION['password']);
       // username/password wrong
         return false;
      }
     // user logged in and correct username/password
      return true;
   }
   // no cookies set
   else{
      return false;
   }
}

$logged_in = loggedIn();
// check if logged
if($logged_in){
   // if logged on already redirect to homepage
     #header("Location: http://www.website.net/homepage.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
       <div id="loginDiv">
         <?php
               include ("loginform.php");
         ?>
   </div>
</body>
</html>

 

<?php
if(isset($_POST['sublogin'])){
session_start();
$username = $_POST['userName'];
$password = md5($_POST['userPass']);

include_once("connect.php");
$ress=mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$rows=mysql_fetch_array($ress);

if(($rows["username"]==$username)&&($rows["password"]==$password)){
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if(isset($_POST['remember'])){
setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
}
echo "<meta http-equiv=\"refresh\" content=\"0;url=http://www.mywebsite.net/homepage.php\" />";
return;
}else{
echo "<font style=\"color:#F00; margin-left:20px\">Wrong username or password</font>";
}
}
?>
<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="0">
<tr><td style="color:#999; font-weight:bold; text-align:right;">Username:</td><td colspan="2"><input type="text" name="userName" height="10" size="15" maxlength="30"></td></tr>
<tr><td style="color:#999; font-weight:bold; text-align:right;">Password:</td><td colspan="2"><input type="password" name="userPass" height="10"  size="15" maxlength="30"></td></tr>
<tr><td align="right" style="color:#999; font-weight:bold; text-align:rigt;">Remember:</td><td align="left" style="padding-left:0"><input style="margin-left:0" type="checkbox" name="remember"></td><td align="right" style="padding-right:5px"><input class="textassubmitbutton" style="text-align:right" type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>

Link to comment
Share on other sites

Thanks for taking a look.

 

I'm really struggling with this though, and it really isn't working!

 

I've combined the whole login onto one simple php file, so that it should be easier to look at. Please, if anyone has time to test it and see if they can fix it, or point me in the direction that i need to go i'd really appreciate it.

 

The file, called testloin.php, is attached to this post.

 

When it is just doing the simple login and redirecting the user to the homepage.php everything is fine, but when i click the remember me box, it flashes up with the screenshot (also attached to this post), and then redirects the user to the homepage. So it actually logs in the user in after the error flashes up, but then, if i close the browser and reopen it, it doesn't keep me logged in, so i can only assume that the cookies haven't been set...

 

This is really dragging on so much, Id REALLY appreciate it if someone could sort me out with the answer...

 

[attachment deleted by admin]

Link to comment
Share on other sites

Can we try changing testlogin.php

echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[php_SELF]\">";

 

to

header("Location: ".$HTTP_SERVER_VARS[php_SELF]);

 

THanks for taking the time to look Ozestretch!

 

I tried that, but unfortunately it didn't have an effect.

 

However... looking at that part of the script did prompt me to move the

if(isset($_POST['sublogin'])){

loop out of the displayLogin() function, and change it to contain a redirect immediately after the setCookie statements...it did mean i had to add a couple of functions printheader() and printfooter(), to make sure the error got printed in the browser in the right place, but other than that IT WORKS!!!!

<?php
if(isset($_POST['sublogin'])){

   if(!$_POST['user'] || !$_POST['pass']){
  printheader();
  displayLogin();
      echo '<br />You didn\'t fill in a required field.';
  printfooter();
  die();
   }

   $_POST['user'] = trim($_POST['user']);
   if(strlen($_POST['user']) > 30){
  printheader();
  displayLogin();
      echo '<br />The username is too long.';
  printfooter();
  die();
   }

   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   // Check error codes
   if($result == 1){
   printheader();
  displayLogin();
      echo '<br />That username doesn\'t exist.';
  printfooter();
  die();
   }
   else if($result == 2){
   printheader();
  displayLogin();
      echo '<br />Incorrect password, try again.';
  printfooter();
  die();
   } else if($result == 0){

   	$_POST['user'] = stripslashes($_POST['user']);
   	$_SESSION['username'] = $_POST['user'];
   	$_SESSION['password'] = $md5pass;

   	if(isset($_POST['remember'])){
   	   setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/");
   	   setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/");
   	}
        // REDIRECT FROM HERE.....IT WORKS!!! 
header("Location: homepage.php");
   }

   echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[php_SELF]\">";
   return;
}
?>

 

Thanks so much for your help! Even if the suggestions didn't solve it, sometimes it just needs someone to give your head a bit of a jolt and make you think of something new!  :D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.