michltm February 2016

wrong path using 'require'

Since moving my website from local to online , I have a path problem using require.

I have pages that call bootstrap.php like this:

require 'inc/bootstrap.php';

And boostrap.php looks like this:

<?php
spl_autoload_register('app_autoload');

function app_autoload($class){
require "class/$class.php";
}

This worked well in local.

Now, online, I get the following message:

Warning: require_once(/home/website/www/class/functions.php): failed to open stream: No such file or directory in /home/website/www/inc/bootstrap.php on line 6

Fatal error: require_once(): Failed opening required '/home/website/www/class/functions.php' (include_path='.:/usr/share/php:/usr/share/pear') 
in /home/website/www/class/functions.php on line 6

So I thought, I should put an absolute path in boostrap.php like this:

<?php
spl_autoload_register('app_autoload');

function app_autoload($class){
$path = $_SERVER['DOCUMENT_ROOT'] . "class/$class.php";
require_once "$path";
}

But I get the exact same error. I dont understand why it is still looking in the /home/website/www/inc/bootstrap.php and not following the absolute path which is /home/website/www/class/functions.php ?

EDIT:

After testing the different solutions using absolute pathes, I am still getting the error that "No such file or directory in /home/website/www/bootstrap.php: so it is still looking in the file instead of directory.

Could it be because I am using a double require? I first require boostrap.php from description.php (which works fine) and then I require class.php from this boostrap.php (which doesent take the absolute path but the path corresponding to the file boostrap.php ?

ANSWER:

Answers


ETech February 2016

  1. As it was said in comments, it is safe to use absolute path instead of 'inc/...', cause it is relative to current class execution path, i.e.:

    define ('BASE_PATH', dirname(__FILE__).'/../');
    

    Then use BASE_PATH.{your_path} to access files.

  2. I suggest to use require_once to avoid multiple inclusions.

Post Status

Asked in February 2016
Viewed 3,707 times
Voted 4
Answered 1 times

Search




Leave an answer