代码中的错误是杀了我[重复]

This question already has an answer here:

The problem is that, even after I have cleared my cookies, it is still displaying the page, which my first if statement is supposed to take care of. Here is the code:

<?php
include('/Applications/MAMP/htdocs/premind/includes/vars.php');

if (!isset($_COOKIE['emailaddress'])) {
    header("location:/premind/notloggedin.php");
}

mysql_connect("$host", "$username", "$password");

mysql_select_db($db_name) or die(mysql_error());

$sql4 = 'SELECT `aname`, `date`, `useremail`, `aid` FROM `data`';

$result4 = mysql_query($sql4) or die("<br />" . mysql_error());

$countrows2 = mysql_num_rows($result4);

if (!$result4) {
    echo "Cannot show assignments!";
}

while ($row = mysql_fetch_array($result4)) {
    if ($row['useremail'] == $_COOKIE['emailaddress']) {
        echo $row['aid'] . ". " . $row['aname'] . " -- " . $row['date'] . "<br />";
        echo "<br />";
    }
    elseif ($countrows2 == 0) {
        echo "<h1>No assignments found!</h1>";
    }
}

if ($countrows2 == 0) {
    echo "<h1>No assignments found!</h1>";
}
?>
</div>

Try

if (!isset($_COOKIE['emailaddress'])) {
   header("Location: /premind/notloggedin.php");
   exit();
}

Might also want to check !empty() just in case.

Also:

mysql_connect("$host", "$username", "$password");

No need for the quotes here.

mysql_connect($host, $username, $password);

Is just fine

On a side note, as ComFreek mentioned, cookies are not a secure way to authorize users.

You need to die() after the header statement. The Location header means nothing if a page comes afterwards.

if (!isset($_COOKIE['emailaddress'])) {
    header("location:/premind/notloggedin.php");
    die();
}

I think there

  • should be space between location & url
  • try using full domain instead,

so try the following code

<?php
if (!isset($_COOKIE['emailaddress'])) {
    header("location: http://" . $_SERVER['HTTP_HOST'] . "/premind/notloggedin.php");
    exit();
}

Let me know if it works or not.

I agree with @Robus as far as implementation goes. You should also verify that include('/Applications/MAMP/htdocs/premind/includes/vars.php'); is not printing anything out, and that you don't have any white space before your <?php tag.

You can use the headers_sent function to determine if the issue is indeed header related

if (!headers_sent($filename, $linenum)) {
   header("Location: /premind/notloggedin.php");
   exit();
} else {
    echo "Headers already sent in $filename on line $linenum";
    exit;
}