Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To understand PHP's header()

Tags:

php

header

Where do you use the command header()?

I have the following code at handlers/handle_login.php. The user has gone to the site from index.php which is the starting place.

 if(!$logged_in){
     header("Location: index.php");                                                                          
     die("You are not logged_in");
 }

If if-clause is true, I get a 404 error, since the header puts me to to handlers/index.php, instead of index.php.

like image 730
Léo Léopold Hertz 준영 Avatar asked Dec 18 '22 06:12

Léo Léopold Hertz 준영


1 Answers

While I agree with nilamo and earl, I hope I can give a bigger picture:

Using relative paths can have very strange effects depending on where the browser 'thinks' it is in your site hierarchy. For example, assume the site has an index file '/index.php' but is configured to accept module and action in the URI path. You may very well have a url that looks like:

http://www.yoursite.com/forms/contact/

From this situation, returning a header like:

header("Location: index.php");

may very well cause the browser to try to request

http://www.yoursite.com/forms/contact/index.php

which is obviously not what you want. For this reason, it's generally better to use '/index.php' as recommended above, or even better use the fully qualified URL when possible.

Hope this helps.

like image 69
Chris Miller Avatar answered Jan 02 '23 12:01

Chris Miller