public
Created

Return dynamic base URL of current file, on domain or within directory.

  • Download Gist
dynamic-base-url.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?php
 
function base_url()
{
/* Get protocol information whether using secure or normal */
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https://' ? 'https://' : 'http://';
/* Call current script */
$path = $_SERVER['PHP_SELF'];
/*
* returns arrays:
* Array (
* [dirname] => /path/
* [basename] => script.php
* [extension] => php
* [filename] => script
* )
*/
$path_parts = pathinfo($path);
$directory = $path_parts['dirname'];
/*
* Replace backslash dirname,
* If it's in main directory only return / if within folder return dirname/
*/
$directory = str_replace('\\', '', $directory);
$directory = ($directory == "/") ? "/" : $directory .'/';
/* return domain name (localhost / domain.com) */
$host = $_SERVER['HTTP_HOST'];
/* Final Output */
return $protocol . $host . $directory;
}
 
echo base_url();
 
/* End of dynamic-base-url.php */

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.