PHP include absolute path

digicom picture digicom · Apr 7, 2014 · Viewed 48.3k times · Source

I have a variable on my site called $basePath which is set as:

$basePath = '/Systems/dgw/';

I am using it on all my css, js and images tags as so (shortened for better visibility):

<link href="<?php echo $basePath; ?>include/assets/css/bootstrap.min.css">

I have no problem with those includes and they work fine in wherever file and in whatever folder I am.

I have a certain included page which has the following line:

<img src="<?php echo $basePath; ?>images/new_logo.png" alt="logo"/>

And the image shows just fine. The line after it states:

<?php include($basePath.'include/assets/common/topMessages.php');?>

But the include doesn't happens. When I try it like this:

<?php include('../../include/assets/common/topMessages.php');?>

It works.

Anybody has any idea what could be wrong?

Answer

Laurent S. picture Laurent S. · Apr 7, 2014

You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :

<?php 
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/yourpath/yourfile.php";
   include_once($path);
?>