Trying to get a full URL without filename in PHP

后端 未结 7 1683
鱼传尺愫
鱼传尺愫 2020-12-31 01:32

I thought this would be simple but I can\'t seem to find a variable of $_SERVER array that has what I\'m looking for.

Let\'s say my url is http://

相关标签:
7条回答
  • 2020-12-31 02:13

    I can't seem to find a variable of $_SERVER array that has what I'm looking for.

    because it's fictional string, existing only in the browser's address bar.
    It's parts being sent to server separated.

    I want to know if there's a var of the _server array

    That's very easy to know. just print_r($_SERVER); really simple.

    I know I could quite easily do this with some string manipulation

    yeah. the code you have to write is less than this question text.

    but with some manual magic it can be reduced to just one function.

    0 讨论(0)
  • 2020-12-31 02:14

    In your case, string manipulation is the best solution.

    For Example:

    substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/') + 1);
    
    0 讨论(0)
  • 2020-12-31 02:22

    This worked perfectly for me and seems to be a very clean solution.

    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $path = $protocol.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
    
    0 讨论(0)
  • 2020-12-31 02:24

    you can use dirname() to get the path of a url.

    0 讨论(0)
  • 2020-12-31 02:29

    There are no defined variables for what you want.

    You can use the code below to get the full base url:

    // Base folder url
    $myBase =  ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    

    but hopefully most times you won't require the full thing just use:

    // Base folder server root path
    $myBase = dirname($_SERVER['PHP_SELF']);
    

    Just be careful if you're using some kind of routes system (mod_rewrite).

    0 讨论(0)
  • 2020-12-31 02:30

    There won't be one because it's not a useful attribute to track. If the current script is something other than index.* then it will not return the correct URL for the current script.

    However, this might get you what you want:

    echo '//'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
    

    Edit:
    Also, aside from installing the php.net online manual search tool for Firefox and setting it up with a search keyword (which will let you pull up the documentation on the $_SERVER global by typing something like "php $_server" into your URL bar), you should also know that var_dump() and print_r() lets you output the full contents of any variable, including arrays and objects. This is very useful for debugging.

    0 讨论(0)
提交回复
热议问题