Is there a simple way to get the requested file or directory without the GET arguments? For example, if the URL is http://example.com/directory/file.php?paramater=value
I would like to return just http://example.com/directory/file.php
. I was surprised that there is not a simple index in $_SERVER[]
. Did I miss one?
(please upvote that answer so it can be more visible).
The simplest solution would be:
echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Parse_url is a built-in php function, who's sole purpose is to extract specific components from a url, including the PATH
(everything before the first ?
). As such, it is my new "best" solution to this problem.
Stackoverflow: How to remove the querystring and get only the url?
You can use strtok to get string before first occurence of ?
$url=strtok($_SERVER["REQUEST_URI"],'?');
Performance Note: This problem can also be solved using explode.
This application of strtok to return everything in a string before the first instance of a character will perform better than any other method in PHP, though WILL leave the querystring in memory.
$_SERVER
varsWhile OP did not ask about it, I suppose it is worth mentioning: parse_url should be used to extract any specific component from the url, please see the documentation for that function:
parse_url($actual_link, PHP_URL_SCHEME);
Of note here, is that getting the full URL from a request is not a trivial task, and has many security implications. $_SERVER
variables are your friend here, but they're a fickle friend, as apache/nginx configs, php environments, and even clients, can omit or alter these variables. All of this is well out of scope for this question, but it has been thoroughly discussed:
https://stackoverflow.com/a/6768831/1589379
It is important to note that these $_SERVER
variables are populated at runtime, by whichever engine is doing the execution (/var/run/php/
or /etc/php/[version]/fpm/
). These variables are passed from the OS, to the webserver (apache/nginx) to the php engine, and are modified and amended at each step. The only such variables that can be relied on are REQUEST_URI
(because it's required by php), and those listed in RFC 3875 (see: PHP: $_SERVER ) because they are required of webservers.
please note: spaming links to your answers across other questions is not in good taste.