I dont understand wat has happened... the code was working fine yesterday when testing, and now i try to use it today, and it doesnt work.
setcookie() isnt setting the cookie... Maybe i have missed something, so hopefully someone here can see where ive gone wrong. Just to confirm though, this was working perfectly fine yesterday...and i hadnt made any changes to it since then so im really confuzzled. Any help will be appreciated..

www.mysite.com is just an example for posting here, it is replaced by the actual site address when testing it. I also understand the security issues in the code below, i dont need help with that, this is just for testing purposes... i just need to understand why setcookie isnt working. Thanks

<?php 
        include "include/config.php";
        $_POST['password'] = addslashes($_POST['password']);
        $user = addslashes($_POST['username']);
        $password = md5($_POST['password']);
        $userrow = mysql_query("SELECT * FROM users WHERE user_username = '".$user."' AND user_password = '".$password."' ");
        ob_start();
        if(mysql_num_rows($userrow) == "1"){
        if (isset($_POST['rememberme'])) {
            setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'www.mysite.com');
            setcookie('password', md5($_POST['password']), time()+60*60*24*365, '/', 'www.mysite.com');
        } else {
            setcookie('username', $_POST['username'], false, '/', 'www.mysite.com');
            setcookie('password', md5($_POST['password']), false, '/', 'www.mysite.com');
        }
        header('Location: index.php');
    } else {
        echo 'Username/Password Invalid';
    }
        ob_end_flush();

?>

Dani AI

Generated

Nice catch by — switching the form action to the full URL is a classic fix because cookies are tied to origin (host + scheme + port) and to the domain/path you set when sending the Set-Cookie header. If the POST target or the page you view ends up on a different host (for example example.com vs www.example.com), the browser may never show or send the cookie where you expect.

Quick troubleshooting checklist (common causes and what to check):

  • Inspect the HTTP response for a Set-Cookie header (Browser DevTools → Network → response headers) to confirm the cookie was actually sent.

  • Host/path mismatch: make sure the script that sets the cookie runs under the same host as the pages that will read it. Hard-coding a domain can cause issues if requests land on a non‑www vs www host. Omitting the domain will default to the current host; using the base domain (e.g., .example.com) covers subdomains.

  • Headers/output: calling cookie functions must happen before output. To debug, detect where output began:

    if (headers_sent($file, $line)) {
        error_log("Headers already sent in $file on line $line");
    }
    error_log(print_r(headers_list(), true)); // shows sent headers including Set-Cookie
  • Redirects: a Location redirect is fine provided the Set-Cookie headers were sent before the redirect.

  • Localhost and privacy: setting a cookie domain on localhost won’t behave the same; browser privacy settings or extensions can block cookies.

Minor correctness/security notes: ’s pointer about type-safe comparisons is helpful for logic. Also avoid storing raw passwords in cookies — use a server-side token, set cookies with HttpOnly/Secure (and an appropriate SameSite) to reduce risk.

Recommended Answers

All 5 Replies

Try removing the quotes from the mysql_num_rows line like the following:

if(mysql_num_rows($userrow) == 1){

Hi, thanks for your reply. I should mention though that, that part of the code works.. i tested that using echo.... it just simply will not set the cookie on the browser after the if statement. I have been searching all day for the solution, but i cannot find it...

Ill post an update of the code:

checkpass.php

<?php include('includes/config.php');
$user = addslashes($_POST['username']);
$password = md5(addslashes($_POST['password']));
$userrow = mysql_query("SELECT * FROM users WHERE user_username = '" . $user . "' AND user_password = '" . $password . "' ");
if (mysql_num_rows($userrow) == "1") {
ob_start();
  if (isset ($_POST['rememberme'])) {
    setcookie('username', $_POST['username'], time() + 60 * 60 * 24 * 365, '/', 'www.mysite.com');
    setcookie('password', md5($_POST['password']), time() + 60 * 60 * 24 * 365, '/', 'www.mysite.com');
  }
  else {
    setcookie('username', $_POST['username'], false, '/', 'www.mysite.com');
    setcookie('password', md5($_POST['password']), false, '/', 'www.mysite.com');
  }
  header('Location: index.php');
ob_end_flush();
}
else {
  echo 'Username/Password Invalid';
}
?>

index.php login form:

<?php
if (islogged()) {
echo '<table style="align: center; width:280px; border:0px; margin-bottom:5px;">
<tr>
<td><div class="title"> Welcome, '.$_COOKIE['username'].'</div></td></tr></table>
';
} else {
echo '
<form method="post" action="checkpass.php">
<table style="align: center; width:200px; border:0px;">
<tr>
<td width="60">Username</td><td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"><br />Remember Me: <input type="checkbox" name="rememberme" value="1"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td></td>
<td>&nbsp;</td>
<td>
<input type="submit" name="submit" value="Login">
</form></td></tr>
</table><div style="margin-bottom:15px;"></div>';
}
?>

the islogged() function, simply tests to see if cookie is set. Im thinking, maybe i have to have a session in progress before i set the cookie? Im not sure, I really havent found anything to confirm it... and trying to use session_start() outputs a header error..

thanks again

I'm not sure what your function islogged() contains but your first page should look more like the following as there are 3 errors:

<?php include('includes/config.php');
$user = mysql_real_escape_string($_POST['username']);
$password = md5(addslashes($_POST['password']));
$userrow = mysql_query("SELECT * FROM users WHERE user_username = '" . $user . "' AND user_password = '" . $password . "'") or die('Error 1: '.mysql_error());
if (mysql_num_rows($userrow) == 1) {
ob_start();
  if (isset ($_POST['rememberme'])) {
    setcookie('username', $_POST['username'], time() + 60 * 60 * 24 * 365, '/', 'www.mysite.com');
    setcookie('password', md5($_POST['password']), time() + 60 * 60 * 24 * 365, '/', 'www.mysite.com');
  }
  else {
    setcookie('username', $_POST['username'], false, '/', 'www.mysite.com');
    setcookie('password', md5($_POST['password']), false, '/', 'www.mysite.com');
  }
  header('Location: index.php');
ob_end_flush();
}
else {
  echo 'Username/Password Invalid';
}
?>

Hi again, thanks for your reply, I really do appreciate your input. I tried your code but nothing happened:(, no cookie got set. I have over yesterday & today, tried everything i could, and have read everything i could on cookies, and have not found the answer. The function islogged() is below, just a simple check to see if the user exists, but has nothing to do with setting the cookie. I just cant figure this out, i have actually installed a sample login script that uses cookies, and the cookies wont set in that script either. The only difference i can think of is that i replaced the login system which used sessions, and before i tested setcookie() i hadnt yet removed session_start() from the top of each page yet. Do you think that would make any difference? Do i need a session in progress to set a cookie? I know im grabbing out of the air here proberly, but i am trying to think of the smallest things that could effect the cookie being set.

Thanks again.

function islogged() {

$id = mysql_query("SELECT * FROM users WHERE user_username = '".$_COOKIE[username]."' LIMIT 1") or die(mysql_error());
while ($rows = mysql_fetch_array($id)) {

if ($rows[user_logged] == 1) {
$logged = 1;
}

  }
return $logged;

}

oh my gawd... i fixed it....
it was the url in the form action. It wasnt directing correctly for some reason. I changed it to the full url address, instead of the "checkpass.php" short version, and vuola...cookies are being set. Im so stupid, i dont know why i didnt think of that earlier... and that was one of the minor details i changed the day before i had the problem..

Thanks again for your help, and see you around:)

*goes off to hav a glass o'vino after that headache

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.