4

I need to modify my function to return also the current folder I am in. Here is my current function:

function getLinkFromHost($url){  
    $port = $_SERVER['REMOTE_PORT'];  
    $server = $_SERVER['HTTP_HOST'];  
    if($port == 443){  
        $type = "https";  
    } else {  
        $type = "http";  
    }  
    return $type . "://" . $server . "/" . $url;  
}
Ikke
  • 99,403
  • 23
  • 97
  • 120
somejkuser
  • 8,856
  • 20
  • 64
  • 130

5 Answers5

8

Take a look at $_SERVER['REQUEST_URI'] or $_SERVER['SCRIPT_NAME']

(From the $_SERVER manual entry)

Mark Biek
  • 146,731
  • 54
  • 156
  • 201
5

Here a short sweet function I've been using to do this for awhile now.

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

I can't take the credit, it belongs to:

http://www.webcheatsheet.com/PHP/get_current_page_url.php

SamuelWarren
  • 1,449
  • 13
  • 28
  • 1
    This is very much the Right Way to do it. Not checking the protocol (HTTP vs HTTPS), port and server name are very often overlooked and can lead to problems later (especially in test environments, or worse 'only in production' if you have SSL enabled for some aspect of it, but not in development). This approach is good practice as it applies regardless of the language being used. – Iain Collins Dec 08 '09 at 15:33
  • Although even HTTPS and SERVER_PORT won't help you if your SSL is done by a load balancer. In that case the URL may look like `https://site.com/`, but HTTPS will be off, and SERVER_PORT could be 80 (or something else). – JW. Feb 20 '10 at 03:18
1

..........

echo $_SERVER['PHP_SELF']; // return current file

echo __FILE__; // return current file

echo $_SERVER['SCRIPT_NAME']; // return current file

echo dirname(__FILE__); // return current script's folder

// etc
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
1

Probably you also want to include get vars into your url, so you should add something to highphilosopher function...

$current_url = rtrim(curPageURL(), "/").(!empty($_GET)) ? "?".http_build_query($_GET) : "";

Kirzilla
  • 16,368
  • 26
  • 84
  • 129
1

Here's a method that might help:

function current_url()
{
    $result = "http";

    if($_SERVER["HTTPS"] == "on") $result .= "s";

    $result .= "://".$_SERVER["SERVER_NAME"];

    if($_SERVER["SERVER_PORT"] != "80") $result .= ":".$_SERVER["SERVER_PORT"];

    $result .= $_SERVER["REQUEST_URI"];

    return $result;
}
Emanuil Rusev
  • 34,563
  • 55
  • 137
  • 201