Jump to content

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. :)
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/
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.
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/#findComment-58177
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...
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/#findComment-58178
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.
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/#findComment-58210
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.
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/#findComment-58223
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.
Link to comment
https://forums.phpfreaks.com/topic/14624-setcookie/#findComment-58233
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.