15

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

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
Steven
  • 24,410
  • 42
  • 108
  • 130

6 Answers6

32

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.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
6

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

adrianTNT
  • 3,671
  • 5
  • 29
  • 35
3

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
  • 772
  • 1
  • 9
  • 25
2

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
  • 3,020
  • 22
  • 32
1

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.

Community
  • 1
  • 1
1

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;
bummi
  • 27,123
  • 14
  • 62
  • 101
Vaibhav Jain
  • 493
  • 2
  • 7
  • 13