Jump to content

Archived

This topic is now archived and is closed to further replies.

treilad

setcookie

Recommended Posts

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:

[code]<?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
}


?>[/code]

It is included in a table on another webpage.

Thanks in advance. :)

Share this post


Link to post
Share on other sites
Dude, didn't you already post this?

EDIT:
http://www.phpfreaks.com/forums/index.php/topic,100572.0.html
Yea, you did...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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...
[code]
<?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;
}
?>[/code]

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

Share this post


Link to post
Share on other sites
:) 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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
i know he said its a bandaid but thats what i have always used and i dont care what he called it lol.

Share this post


Link to post
Share on other sites
[quote]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.[/quote]

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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*

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

×

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.