tags:

views:

117

answers:

4

How do I get the current URL of my script using PHP?

+7  A: 

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 = (!empty($_SERVER['HTTPS']))
    ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] 
    : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

Note: You should groom this value before using in anything sensitive, like a sql query.

Andrew Hare
+2  A: 

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.

Brimstedt
A: 

suppose you were accessing

http://stackoverflow.com/questions/1871770/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.

ravindrakhokharia
Don’t use *PHP_SELF*.
Gumbo
yes... 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
not to mention that PHP_SELF is vulnerable to XSS.
Josh Sandlin
A: 

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.

Hitesh Chavda