Re: Redirecting in a PHP script

From: Date: Mon, 12 Mar 2007 21:43:44 +0000
Subject: Re: Redirecting in a PHP script
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-250328@lists.php.net to get a copy of this message
----- Original Message ----- From: "Larry Bradley" <lhbradley@igs.net> To: <php-general@lists.php.net> Sent: Monday, March 12, 2007 9:02 PM Subject: [PHP] Redirecting in a PHP script
I need to "goto" different PHP pages in my web site depending on what happens within some PHP code. For example, if the user is not logged in when he goes to a page, I want to send him to a LOGIN page. I've have everything working fine, using the following Javascript code:
            $location = 'login.php';
                echo "<script language='javascript'>\n";
                echo "document.location.href = '" . $location . "';\n";
                echo "</script>\n";
I also played around with using the header("location: ...") function. I understand that the header() function must be issued before any HMTL is output. But I'm not sure about the Javascript code. In every instance in my code, I use the Javascript before any HTML - this type of action normally occurs in PHP code called via a form POST. I presume that the Javascript code really does the same as the PHP stuff, and thus must obey the same rules, but I'm not sure. Comments? Larry Bradley Orleans (Ottawa), Ontario, CANADA
The header function fails if anything at all is sent to the browser, be it plain HTML, JavaScript code or even a single space. The header function does not differentiate between the visible part of the page (that within the <body>) or what goes before, it fails even if a whitespace is sent before the <html> or <!doctype declaration. A redirect via JavaScript can be done at any time and it is no different than a user clicking on a <a href=> tag. It will be executed when found or when invoked. If not contained within a function, it will be executed at once, no matter if the full page has not been loaded yet. If within a function, whenever it is called. Notice, though, the effect on the History. The header() call will have only the destination page stored on the History, the JavaScript will have both the original and the final destination. Thus, redirecting with JavaScript will get you into a loop if after reaching the destination you click on the back button, because you will fall in the page containing the redirection. I'm sure you found places like that. The only way to actually go back in those is to open the dropdown list for the back button and skip over one item. That does not happen when using the header() PHP function. Satyam

« previous php.general (#250328) next »