How do I get the current URL of my script using PHP?
6 Answers
Please see PHP Get Current URL:
Sometimes it is not as straightforward as one may think to get the current url to use it inside your application. Here is a snippet that I use to fetch the current URL and use it in a script. The current url (whether http or https) is now a local variable that you can do with as you please.
$url = "http".(!empty($_SERVER['HTTPS'])?"s":"").
"://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
Note: You should groom this value before using in anything sensitive, like a sql query.

- 7,449
- 2
- 29
- 45

- 344,730
- 71
- 640
- 635
-
server port is missing.. – aLx13 Feb 24 '17 at 11:24
-
1if you use rewrite to add variables after the script, like /x.php/123/456 then using REQUEST_URI will include those parameters. SCRIPT_NAME might be better. – Ellert van Koperen Sep 15 '17 at 11:20
-
Link is dead... – ericek111 Dec 17 '19 at 13:27
For www.example.com/files/script.php
$_SERVER['SCRIPT_NAME']
= /files/script.php
and if you want the current directory url:
dirname($_SERVER['SCRIPT_NAME'])
= /files

- 3,671
- 5
- 29
- 35
If you want to know the script name on your server, then..
$file = $_SERVER["SCRIPT_NAME"];
echo $file;
$_SERVER["SCRIPT_NAME"] will give you the current executed script path, which related on your server not on the browser's url.

- 772
- 1
- 9
- 25
Whe you need info like this its often convenient to look at the output of phpinfo() and then read the docs on those items that seems good.
Keep in mind that some of them might be correct on your server, but slightly different on others.. Depending on os, http server etc.

- 3,020
- 22
- 32
suppose you were accessing
How do I get the current URL of my script using PHP?
then
echo $_SERVER['SERVER_NAME']; // This will return u the hostname that is:-
stackoverflow.com/
and
echo $_SERVER['REQUEST_URI']; // It will return only the file name from current url
will return below
"/questions/1871770/how-do-i-get-the-current-url-of-my-script-using-php"
and not the hostname.

- 1
- 1

- 174
- 1
- 9
-
1yes... PHP_SELF would only return the file... and not the other parameters.. and if one needs full path then he has to use "REQUEST_URI", and i have edited my answer.. – ravindrakhokharia Dec 11 '09 at 04:26
-
2
Hi this is the solution of your problem
//fetch page url by this
$url=$_SERVER['REQUEST_URI'];
echo "$url<br />";
//it will print
//fetch host by this
$host=$_SERVER['HTTP_HOST'];
echo "$host<br />";
//you can fetch full url by this
$fullurl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $fullurl;

- 27,123
- 14
- 62
- 101

- 493
- 2
- 7
- 13