To understand PHP's header()

前端 未结 3 1619
南笙
南笙 2020-12-19 16:53

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

相关标签:
3条回答
  • 2020-12-19 17:01

    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.

    0 讨论(0)
  • 2020-12-19 17:13

    Try using '/':

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

    Without a slash, it is assumed that you're referring to something in the current directory. By sticking that slash at the front, you're explicitly referring to the file at the root of the site. Since the page is 'index.php', you could just as easily use "header('Location: /')".

    0 讨论(0)
  • 2020-12-19 17:16

    Set the location to the complete URL of the index.php, not just the filename. According to php.net, this is the right way to do it, don't use relative paths. Here is an example:

     if(!$logged_in){
         header("Location: http://exampledomain.com/index.php");
         die("You are not logged_in");
     }
    
    0 讨论(0)
提交回复
热议问题