Jump to content


Photo

setcookie


  • Please log in to reply
12 replies to this topic

#1 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 11:28 PM

I have a login script that sets a cookie when they login.

I get the 'headers cannot be sent' error because I am trying to send headers /after/ info has already been sent to the browser. The login script is included() within a webpage, so I'm told to put the setcookie at the top of the page. But now I don't understand why I'd set a cookie on the login page before they've logged in.

This is obviously very common script because it's used on so many websites. I'm just missing something. Could someone please explain it to me, perhaps a little more step-by-step than you would with a normal question? I'm somewhat new to PHP so obvious things aren't quite so obvious with me.  ;)

Here is my login script:

<?php

include ('db.php');

if(isset($_COOKIE['ID_my_site']))

{ 
	$username = $_COOKIE['ID_my_site']; 
	$pass = $_COOKIE['Key_my_site'];
	
	$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());

	while($info = mysql_fetch_array( $check )) 	
		{

		if ($pass != $info['password']) 
			{
			
			}

		else
			{
			header("Location: index.php");

			}

		}

}


if (isset($_POST['submit'])) { // if form has been submitted


	if(!$_POST['username'] | !$_POST['pass']) {
		die('You did not fill in a required field.');
	}

	// checks it against the database

	if (!get_magic_quotes_gpc()) {
		$_POST['email'] = addslashes($_POST['email']);
	}

	$check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

$check2 = mysql_num_rows($check);
if ($check2 == 0) {
		die('That user does not exist in our database. <a href=registration.php>Click Here to Register</a>');
				}


while($info = mysql_fetch_array( $check )) 	
{

$_POST['pass'] = stripslashes($_POST['pass']);
	$info['password'] = stripslashes($info['password']);
	$_POST['pass'] = md5($_POST['pass']);


	if ($_POST['pass'] != $info['password']) {
		die('Incorrect password, please try again.');
	}

else
{
	
$_POST['username'] = stripslashes($_POST['username']);
	

$hour = time() + 3600; 
setcookie(ID_my_site, $_POST['username'], $hour);
setcookie(Key_my_site, $_POST['pass'], $hour);	

header("Location: index.php");
}

}

} else {	

?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}


?>

It is included in a table on another webpage.

Thanks in advance. :)

#2 pixy

pixy
  • Members
  • PipPipPip
  • Advanced Member
  • 295 posts

Posted 14 July 2006 - 11:30 PM

Dude, didn't you already post this?

EDIT:
http://www.phpfreaks...c,100572.0.html
Yea, you did...

This is a .44 Caliber Loveletter straight through my heart.

Tabulas + Threadless + Hire Me!


#3 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 11:32 PM

I did, asking a somewhat different question. I deleted it and rephrased the question because I wasn't getting the answer I needed.

They told me I needed to set the cookie or session at the beginning, which I'm trying to do. I just don't understand how to make the script work with that.

#4 pixy

pixy
  • Members
  • PipPipPip
  • Advanced Member
  • 295 posts

Posted 14 July 2006 - 11:33 PM

As I said in that thread also, you need to setcookie(); before you send ANYTHING to the browser. Even whitespace gives you errors.

To redirect to pages, I use this function so I dont have to deal with headers...
<?php
function redirect($path, $timeout=2, $type=X_REDIRECT_HEADER) {

    // Make sure the session isn't split
    if (strpos(urldecode($path), "\n") !== false || strpos(urldecode($path), "\r") !== false)
    {
        error('Tried to redirect to potentially insecure url.');
    }

    // force session to be written before redirecting
    session_write_close();

    $type = (headers_sent() || $type == X_REDIRECT_JS ) ? X_REDIRECT_JS : X_REDIRECT_HEADER;
    if ($type == X_REDIRECT_JS) {
        ?>
        <script language="javascript" type="text/javascript">
        function redirect() {
            window.location.replace("<?php echo $path?>");
        }

        setTimeout("redirect();", <?php echo ($timeout*1000)?>);
        </script>

        <?
    } else {
        if ( $timeout == 0) {
            header("Location: $path");
        } else {
            header("Refresh: $timeout; URL=./$path");
        }
    }
    return true;
}
?>

Just store it in a functions.php and include it somewhere if you want to use it...

This is a .44 Caliber Loveletter straight through my heart.

Tabulas + Threadless + Hire Me!


#5 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 11:36 PM

That's what I needed to know. Thanks. :)

#6 BillyBoB

BillyBoB
  • Members
  • PipPipPip
  • Advanced Member
  • 630 posts

Posted 14 July 2006 - 11:55 PM

or put
<?php
ob_start();
?>

before anything else

#7 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 15 July 2006 - 12:33 AM

:) The post about headers by akitchen said that that was a bandaid. I've been working on this for long enough that I don't care. Bandaid's fine. Thanks, BillyBob.

#8 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 15 July 2006 - 12:43 AM

i hope that eventually you realize why the errors are occurring, and how to avoid the headache in the future without using output buffering (which, used in more complex scripts, is a can of worms all on its own).

generally speaking, one should operate any server-side procedures before outputting anything to the browser.  validate the form, do whatever you want to with the info, and set some content into variables.  THEN go about sending out the typical static stuff plus any feedback from your procedures (success, errors, a form if there were errors, etc.).  structuring your scripts this way just makes debugging, reading, and editing a crapload easier in the end.

in short, solving a problem like this at the root means less time pulling out your hair, yelling at the monitor and asking in the forums.  it also means more time getting on with your work.

#9 BillyBoB

BillyBoB
  • Members
  • PipPipPip
  • Advanced Member
  • 630 posts

Posted 15 July 2006 - 12:51 AM

i know he said its a bandaid but thats what i have always used and i dont care what he called it lol.

#10 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 15 July 2006 - 12:59 AM

i hope that eventually you realize why the errors are occurring, and how to avoid the headache in the future without using output buffering (which, used in more complex scripts, is a can of worms all on its own).

generally speaking, one should operate any server-side procedures before outputting anything to the browser.  validate the form, do whatever you want to with the info, and set some content into variables.  THEN go about sending out the typical static stuff plus any feedback from your procedures (success, errors, a form if there were errors, etc.).  structuring your scripts this way just makes debugging, reading, and editing a crapload easier in the end.

in short, solving a problem like this at the root means less time pulling out your hair, yelling at the monitor and asking in the forums.  it also means more time getting on with your work.


Duly noted. :) Thanks for all the tips and while I don't like resorting to temporary fixes, I'm not learned enough in PHP to be able to fix things without assistance. I'm not running a complicated script so this will be fine for now. Once I get to the point where I can honestly say I know what I'm doing, I'll make it neat. Thanks again.

#11 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 15 July 2006 - 01:20 AM

thanks for hearing me out treilad.  for what it's worth, i've amended my pinned topic to offer a clearer illustration of the issue and how to fix it, in case you get to the point where you're designing a script from scratch.  i realize how much of a pain it is to restructure code after the fact, and have to shift this and that everywhere.

#12 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 15 July 2006 - 01:32 AM

Perfect! Much more reader-friendly. Makes sense to me now, and you included other things that I'm glad you did. Such as the <meta>/header difference. Thanks so much.

:D

*runs to fix code*

#13 pixy

pixy
  • Members
  • PipPipPip
  • Advanced Member
  • 295 posts

Posted 15 July 2006 - 01:47 AM

I think it's easier to use without ob_start(); and ob_flush();, since those are just more things to remember. Its not THAT hard.

Plus i made my own redirect() function, so I dont need to worry about using header("location: url.php"); Very handy.

This is a .44 Caliber Loveletter straight through my heart.

Tabulas + Threadless + Hire Me!





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users