Skip to content

Instantly share code, notes, and snippets.

@aligoren
Created December 31, 2016 11:34
Show Gist options
  • Save aligoren/12dd068a5845e021a59ecc6a18b8c493 to your computer and use it in GitHub Desktop.
Save aligoren/12dd068a5845e021a59ecc6a18b8c493 to your computer and use it in GitHub Desktop.
Get Base URL / Path with PHP
<?php
/*
It works these urls:
Without sub dir
http://site.com/index.php
http://site.com/index.php/
With sub dir
http://site.com/sub/index.php
http://site.com/sub/index.php/
http://site.com/sub/other_sub/index.php
http://site.com/sub/other_sub/index.php/
*/
require_once 'url.php';
class Home
{
use URL;
}
$h = new Home();
?>
<a href="<?=$h->get['base_url']?>">Base</a>
<?php
trait URL {
private $url = '';
private $current_url = '';
public $get = '';
function __construct()
{
$this->url = $_SERVER['SERVER_NAME'];
$this->current_url = $_SERVER['REQUEST_URI'];
$clean_server = str_replace('', $this->url, $this->current_url);
$clean_server = explode('/', $clean_server);
$this->get = array('base_url' => "/".$clean_server[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment