Reputation: 343
Is there any explanation of this strange behavior of defined constant?
I have 1 file (config.php
) which hold predefined value of directories, something like this
$dir = array
(
'core_dir' => 'includes',
'admin_dir' => 'admin',
'upload_dir' => 'uploads',
'template_dir' => 'templates'
);
define('SCRIPT_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR );
foreach($dir as $name => $location)
{
if ( !is_dir($location) AND is_dir(SCRIPT_DIR.$location))
$dir[$name] = SCRIPT_DIR.$location;
}
define('CORE_DIR',$dir['core_dir'].DIRECTORY_SEPARATOR);
define('ADMIN_DIR',$dir['admin_dir'].DIRECTORY_SEPARATOR);
define('UPLOAD_DIR',$dir['upload_dir'].DIRECTORY_SEPARATOR);
define('TEMPLATE_DIR',$dir['template_dir'].DIRECTORY_SEPARATOR);
file layout as follow
+root_dir
|_index.php
|_config.php
+-includes
| |_javascript.js
+-admin
|_index.php
This file then included on index.php and /admin/index.php. When I use this constant on main directory:
echo $config['site_url'].CORE_DIR.'js/javascript.js';
with $config['site_url']
was full site URL. It works perfectly:
http://localhost/elearning/includes/js/javascript.js
//which means CORE_DIR = includes/
However when I use the same code under admin directory, I get:
http://localhost/elearning//home/bam/www-data/elearning/includes/js/javascript.js
//which means CORE_DIR = /home/bam/www-data/elearning/includes/ o.O
I know that the based on the config, when relative path not found, it will automatically change to absolute path before the constant defined. But how come same code run on same machine give different output when working on different directory?
Is there something wrong with my code?
Any help would be appreciated.
Upvotes: 1
Views: 461
Reputation: 449843
When you run this from index.php
, the CORE_DIR
constant is not added because the condition
if ( !is_dir($location) AND is_dir(SCRIPT_DIR.$location))
is not met (because $location
exists).
When you run it from another directory, is_dir($location)
is not true any more.
You should remove the first check. That said, I'm not sure whether the whole construction makes sense. Why not use absolute URLs from the start?
Upvotes: 1