PHP - Problem with cookies/setcookie
I'm having problems with the following code: http://pastebin.com/MCkhzQjs
This works locally (on localhost) but when I upload it to the server it does not login. I think it is to do with cookies not being sent. The meta 开发者_如何学编程refresh is so that the page is refreshed after the cookie is set. Thank for any help.
the answer is simple.
You can only set cookies, start sessions, set headers IF there has been not content echo'd or sent (including html) outside of php code blocks.
Examples:
Won't Work:
<div>
<?php setcookie(/*....*/); ?>
</div>
Reason: Because the <div>
has already been sent forcing the headers to be sent, there for cookies cannot be added to the headers, because there sent
Another:
<?php
setcookie(/*....*/); //works
echo "test";
setcookie(/*....*/); //does not
?>
Your code should look like:
$title = "Admin panel";
if(!isset($_COOKIE['login'])) $_COOKIE['login'] = false;
if(!isset($_POST['password'])) $_POST['password'] = false;
if($_POST['password'] == "tt83df")
{
if(isset($_POST['permlog']))
{
$expire = time()+60*60*24*365;
setcookie("login", "tt83df", $expire, "/admin");
}
else
{
setcookie("login", "tt83df", 0, "/admin");
}
header("Location: " . $_SERVER['PHP_SELF']);
exit;//Stop here and SEND Headers
}
if($_COOKIE['login'] == "tt83df")
{
$html = '<ul><li><a href="news_panel.php">News control panel</a></li><li><a href="video_panel.php">Video control panel</a></li><li><a href="schedule_panel.php">Schedule control panel</a></li>
<li><a href="events_panel.php">Events control panel</a></li><li><a href="notices_panel.php">Notices control panel</a></li></ul>';
}else
{
$html = 'Password:<form method="post"><input type="password" name="password" /><input type="submit" value="Submit"><br />
<input type="checkbox" name="permlog" value="true" /> Stay logged in? (do not use on a public computer)</form>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/vnd.microsoft.icon" href="images/favicon.ico" />
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $html; ?>
</body>
</html>
Have you error_reporting enabled? Your code contains whitespaces before the first php-tag, what is an output and forces the server to send the headers(error_reporting should give you a notice about that).
I think that the issue consist of setting a cookie after writing HTML to the output stream. Cookies or header modifications can only done before the header is sent. Writing content to the output stream forces the header to be automatically written.
Try using ob_start();
at the top of your code, and ob_end_flush();
at the bottom. This will initialize a buffer which will be filled with everything that is written to your output stream. So basically. ob_start
is for initializing an output buffer, and ob_end_flush
for writing the buffer back to the client.
精彩评论