Search code examples
phpinclude-path

Why is require_once not working


I'm working on a community written in PHP. I was just going to start working on a chat, so I created a new folder within the root one called "chat". And in that chat folder I created an "index.php" file. In that index.php file I wanna

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

The require_once fucntion works, but within my init.php file I

require_once 'functions/sanitize.php'.

this gives an error

Warning: require_once(functions/sanitize.php) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\ooplr\core\init.php on line 26

Line 26 is

require_once 'functions/sanitize.php'.

Any ideas?

https://i.sstatic.net/h2mtQ.png

Regards,

Gustaf


Solution

  • The best thing to do in a project like this is to define a constant pointing to the current working directory and then use it throughout your app.

    For example, consider the following:

    chat/index.php

    <?php
    
    // Constants
    define('CWD', getcwd()); // points to C:/wamp/www/ooplr/chat
    
    // Load Init Script
    require CWD .'/../core/init.php'; // points to C:/wamp/www/ooplr/core/init.php
    
    // Rest of code ...
    
    ?>
    

    core/init.php

    <?php
    
    // Load Sanitizer
    require CWD .'/../functions/sanitize.php' // points to C:/wamp/www/ooplr/functions/sanitize.php
    
    // Rest of the code
    
    ?>
    

    etc...


    Alternatively...

    chat/index.php

    <?php
    
    // Constants
    define('BaseDir', getcwd() .'/../'); // points to C:/wamp/www/ooplr/
    
    // Load Init Script
    require BaseDir .'core/init.php'; // points to C:/wamp/www/ooplr/core/init.php
    
    // Rest of code ...
    
    ?>
    

    core/init.php

    <?php
    
    // Load Sanitizer
    require BaseDir .'functions/sanitize.php' // points to C:/wamp/www/ooplr/functions/sanitize.php
    
    // Rest of the code
    
    ?>