Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get a full URL without filename in PHP

Tags:

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://example.com/subdirectory/index.php I want to get all but the filename - http://example.com/subdirectory/.

I know I could quite easily do this with some string manipulation, but I want to know if there's a var of the _server array that I'm just missing. I've tried all of them to see what they give and I can get anything BUT what I'm looking for.

like image 777
MrVimes Avatar asked Aug 30 '10 16:08

MrVimes


People also ask

How to store URL in variable in php?

Use the parse_url function of php. Show activity on this post. You can use the $_SERVER globals to get this info. $_SERVER["REQUEST_URI"] should give you new/id=2 and the full (GET) request URI.


2 Answers

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.

like image 68
Lèse majesté Avatar answered Oct 05 '22 11:10

Lèse majesté


In your case, string manipulation is the best solution.

For Example:

substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '/') + 1); 
like image 31
Jack Fuchs Avatar answered Oct 05 '22 09:10

Jack Fuchs