tags:

views:

103

answers:

5

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;  
}
+7  A: 

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

(From the $_SERVER manual entry)

Mark Biek
+5  A: 

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

highphilosopher
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
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
+1  A: 

..........

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
+1  A: 

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
+1  A: 

I've been using:

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