PHP: Get Script’s Absolute Location/Directory Location


I was curious to get the absolute location (the path beginning with http://) of my Script. In another case, I only needed the Directory location of my script, (that means in this case I didn’t want my filename.php in the path). So I wrote a function to do both of the jobs quite easily ;)

<?php

function current_URL($dironly = false)
{
/*
* if No argument is passed, returns full path of current script, i.e. http://server.com/dir/file.php
* else returns dir of current script, i.e http://server.com/dir/
*/

$cur_URL = "http://" .  $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(!$dironly )
return $cur_URL;
else
return dirname($cur_URL) . "/";
}

// USAGE
$myScriptPath = current_URL(); // Gives the path including your script-file-name.php

$myScriptPath = current_URL(true); // Gives the path NOT including your script-filename.php
?>
Advertisements

One thought on “PHP: Get Script’s Absolute Location/Directory Location

Comments are closed.