J. Robinson
J. Robinson

Reputation: 929

Folder Path issues when requiring files

So, I followed a PHP OOP Tutorial on YouTube which was good, got me the code i needed, but now I'm trying to implement it into my site, and i'm having a bit of an error problem.

Here's my folder structure so you can see whats going on. The root folder 'modelawiki' is within my 'htdocs' folder within a XAMPP Localhost Server. I have other sites in other folders within my 'htdocs' folder. https://i.sstatic.net/lrsx3.jpg

In my index.php file within my root folder (modelawiki), I'm requiring my 'core/init.php' file using the following code:

require_once 'core/init.php';

Which executes just fine. But when I move into my 'admin' folder and try to execute:

require_once '../core/init.php';

I'm coming up with the following error:

Warning: require_once(functions/sanitize.php): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/modelawiki/core/init.php on line 31

Fatal error: require_once(): Failed opening required 'functions/sanitize.php' (include_path='.:/Applications/XAMPP/xamppfiles/lib/php') in /Applications/XAMPP/xamppfiles/htdocs/modelawiki/core/init.php on line 31

Heres my 'core/init.php' code:

// Auto Load Classes
spl_autoload_register(function($class) {
    require_once 'classes/' . $class . '.php';
});

// Load Functions
require_once 'functions/sanitize.php';

How would I fix this issue in my 'core/init.php' file to be able to load from within the root folder, and any deeper folders within my folder tree? I also need to make sure that once I upload this to my Network Solutions FTP server that it will run as well.

Upvotes: 1

Views: 98

Answers (2)

Buwaneka Sudheera
Buwaneka Sudheera

Reputation: 1417

I think you should change init.php file as below. You have to give the path correctly.

require_once '../functions/sanitize.php';

Upvotes: 0

user7984880
user7984880

Reputation: 351

You could use absolute paths instead:

  1. get directory of root in your classloader

    // if called in core/init.php
    // the following will be the absolute path of whatever folder core is in
    $rootdir = dirname(dirname(__FILE__));
    
  2. so from there you'll have something like this:

    $rootdir = dirname(dirname(__FILE__));
    
    // Auto Load Classes
    spl_autoload_register(function($class) {
        require_once $rootdir . 'classes/' . $class . '.php';
    });
    
    // Load Functions
    require_once $rootdir . 'functions/sanitize.php';    
    

Upvotes: 1

Related Questions