You are here! How hard can it be?

July 20, 2009 by nuno costa 1 comment Stumble It del.icio.us

I have been asking this question for years, why does web applications keep asking me to config my site url and physical path?

Is this some kind of bad joke, a secret revenge from the developers on those using the software?

Why? How hard can it be?

Not that hard I think, just take a look at $_SERVER['SCRIPT_FILENAME '] or __FILE__ magic constant

  • $_SERVER['SCRIPT_FILENAME '] returns “The absolute path of the currently executing script.
  • __FILE__ returns “The full path and file name of the file. If used inside an include, the name of the included file is returned.

This means that $_SERVER['SCRIPT_FILENAME'] returns the path of the main script, the one called from the URL and __FILE__ returns the path for the actual file where it is called

Knowing this it couldn’t be that hard for configuration scripts find out the physical path, so why it’s never implemented ?

Finding the Url is also very simple using $_SERVER['SERVER_NAME '] and $_SERVER['SCRIPT_NAME ']

It’s just me or every web application could at least present the user with those values by default ?

Here it is, a simple config class witch can find where the hell it’s located and parse ini files

This class is extremely flexible, you can let it fond out the paths for you or you can overwrite it, also it parses ini files and let you have categories

[Site]
    charset="Utf-8"
    authorName="Sven"
    authorEmail = "My@Email.com"
 
[Databse]
    user = "MyUser"
    password="MyPassword"
    host="localhost"

And use it like this

Config::get('Site/authorName');

so here it is

/**
 * Config - ini file configuration class for php
 *
 * @version		0.1
 * @author		Nuno Costa - sven@francodacosta.com
 * @copyright	        Copyright (c) 2007
 * @license		GPL v3 - http://www.gnu.org/licenses/gpl-3.0.html
 * @link		http://www.francodacosta.com/php/you-are-here-how-hard-can-it-be
 */
 
class Config{
    /**
     *
     * @var String - the relative path of the config file (relative from this file path)
     */
	public static $file = '../config/configuration.php';
 
	/**
	 *
	 * @var Array - containing all configuration values
	 */
	public static $conf = array();
 
	/**
	 *
	 * @var boolean - have already loaded the config file ?
	 *  set to false to force a reload
	 */
	public static $loaded = false ;
 
	//Just making sure this class is never instanciated
	private function __construct(){}
 
	/**
	 *
	 * @param String $path - The config path in the form "/<" ex: "Databse/Host"
	 * @return mixed - the value found on $path
	 */
	function get($path ){
 
		if (! self::$loaded){
			self::load();
		}
 
		$keys = explode('/', $path);
		$tmp= array();
		$tmp = self::$conf;
 
		foreach ($keys as $key) {
			$tmp = $tmp[$key];
		}
		return $tmp;
	}
 
	/**
	 *
	 * @return String - the current URl as called by the user ex: https://francodacosta.com
	 */
	private function getUrl(){
	        $protocol='http';
			if ( key_exists('HTTPS', $_SERVER) ){
			    $_SERVER["HTTPS"]  == 'on' ? $protocol='https' : $protocol='http';
			}
			$hostname = self::getHostname();
			$ws_base = self::getWebserverBase();
 
			return str_replace('//', '/',  $protocol . ':////'.$hostname.'/'. $ws_base );
		}
 
	/**
	 *
	 * @return String - The server name
	 */
	private 	function getHostname(){
			return $hostname = $_SERVER['SERVER_NAME'];
		}
 
	/**
	 *
	 * @return String - the current base path of the main script ex: /blog
	 */
	private 	function getWebserverBase(){
			return dirname( $_SERVER['SCRIPT_NAME']);
		}
 
	/**
	 *
	 * @return String - The physical path fo the main script ex: /home/francodacosta.com
	 */
	private 	function getFisicalPath(){
			return dirname($_SERVER['SCRIPT_FILENAME']);
		}
 
	/**
	 * Parses the ini file
	 *
	 * @param $file - the relative path of the confi file
	 * @return Array - ann array with all the config file options
	 */
	private 	function loadfile($file){
			// we are in base_path/system/lib/config.php
			$me = str_replace('\\','/', dirname(__FILE__)); //normalize path
			$sysbase = basename(dirname ($me));
 
			$filename = $sysbase .'/'. $file;
 
			return parse_ini_file( $filename ,true );
		}
 
	/**
	 * Loads Configuration values, and add Path information, if not present in file
	 * @return none
	 */
	public function load(){
 
		$conf=Array();
 
		$conf = self::loadfile(self::$file);
 
		if(! key_exists('Path', $conf) ) $conf['Path'] = array();
		if(! key_exists('Url',$conf['Path']) ) $conf['Path']['Url'] = self::getUrl();
		if(! key_exists('SSLUrl',$conf['Path']) ) $conf['Path']['SSLUrl'] = str_replace('//', '/',  'https:////'.self::getHostname().'/'. self::getWebserverBase() );
		if(! key_exists('Physical',$conf['Path']) ) $conf['Path']['Fisical'] = self::getFisicalPath();
		if(! key_exists('Hostname',$conf['Path']) ) $conf['Path']['Hostname'] = self::getHostname();
		if(! key_exists('WebserverBase',$conf['Path']) ) $conf['Path']['WebserverBase'] = self::getWebserverBase();
 
		self::$conf = $conf ;
                self::$loaded = true ;
	}
}

Usage :

index.php

include "inc/config.php" ;
CONFIG::$file =  "../configuration.ini";
//assuming config file is located in the same folder than index.php.
//Remember the config file path must be relative to the config.php file
 
echo CONFIG::get('Site/authorName');
echo CONFIG::get('Path/Url');
echo CONFIG::get('Path/Physical');

1 comment so far Add Your Comment

  1. [...] path and its URL) we need to know the root physical path and URL of your web site, (there is an easy and automatic way to do this) that will be the most tricky situation you will [...]

More from francodacosta.com

© francodacosta.com - All rights reserved