PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I've been reading a fair amount about the issue of not being able to set a cookie after header information has already been sent in Windows, but I'm not finding a good explanation as to how to structure code based on this concept. I am putting together a simple login form, where, if the username/password combo matches against a database table, it creates a cookie and sends the user to a secure page. I want to cut down on the number of .php pages and keep the code well-organized, but I keep running into the header issue. Can somebody explain how I would modify the code below to not encounter these header issues?
//BEGIN PHP FILE
<? function ShowLoginForm() { ?>
// STANDARD HTML FORM FIELDS FOR USERNAME,PASSWORD, SUBMIT BUTTON
<? } ?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<?
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
ShowLoginForm();
} else {
if (USERNAME AND PASSWORD MATCH BASED ON AUTH FUNCTION) {
***
Here is where I am unclear on what I need to do; Since the user has passed the test here,
I want to set the cookie and redirect them to the secure page. The below does not work. *****
setcookie("loggedin", $username, time()+28800, "/") or die("Could not set cookie");
header("Location:home.php");
} else {
echo "Username/Password Do Not Match";
ShowLoginForm();
}
}
?>
</BODY>
</HTML>
I was guilty of this myself in the beginning, but I wonder why it is that a lot of people think they can send a header in the middle of a page.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
scrotaye wrote:I was guilty of this myself in the beginning, but I wonder why it is that a lot of people think they can send a header in the middle of a page.
As a way of explanation, I think that I, as an ASP guy, naturally look for the equivalent of Response.Redirect, and, unless I'm missing something, header() seems the closest thing in PHP, but, since the latter deals with header information of documents, it really is a totally different thing altogether, but that may be why people end up in this situation like me.