Re: Redirecting in a PHP script

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 3/12/07, Larry Bradley <lhbradley@xxxxxxx> wrote:
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

Just to throw my two cents into this...

I set my scripts up so they run something like this:
class SomePage {
function process($controller) {
if (! logged in)
  return $controller->foward('Login', 'Form');
[page code]
}
}

This way I don't have to issue header redirects to make a user see a
totally different part of the script.  I just tell the controller to
foward the request to another controller action.  You could use this
method on saving records where the post page can redisplay the form on
an error.

The only time I use header redirects is when I don't want the user to
accidentally resubmit the form when they click the back button or if I
need to change the url to remove a variable from it.

On any of my pages that accept POST data I issue a redirect to a page
that thanks the user.  This way they can hit refresh all day and I
don't get extra posts or that nasty page has expired message in IE.

One thing you might also want to consider is the fact people can turn
off JavaScript.  Spam bots also do not have JavaScript.  Anything that
is important such as making sure a user is logged in should have a
server side check otherwise they will blaze right past your JS
redirect.

To do something like the controller above in procedural code it would
be easy enough:

---page.php---
if (! logged in) {
   require 'templates/login_form.php';
} else {
   echo 'user is logged in and okay!';
}
---

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux