PHP Get The Current URL Path

I am not quite sure PHP has inbuilt function for this requirement. While I was coding script for PayPal integration, I had to notify PayPal for IPN url for acknowledging the payment. The IPN script was located elsewhere, ie, on another directory, so I used a custom function to get the current URL path and added the IPN file location to that url. This code will make sure that it return the correct URL even through you are running webserver on non-standard port ( ie, other than port 80).

function getcurrentpath()
{   $curPageURL = "";
    if ($_SERVER["HTTPS"] != "on")
            $curPageURL .= "http://";
     else 
        $curPageURL .= "https://" ;
    if ($_SERVER["SERVER_PORT"] == "80")
        $curPageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     else 
        $curPageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        $count = strlen(basename($curPageURL));
        $path = substr($curPageURL,0, -$count);
    return $path ;
}

echo getcurrentpath();

For example, the script is located at

http://whmphp.com/demo/demo1/demo3/index.php

Then the output will be

http://whmphp.com/demo/demo1/demo3/

You can tweak the script according to your requirements (such as removing the trailing slash). Enjoy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>