1

i have following folder structure.

enter image description here

config.php

<?php
class config {
    const server = "localhost";
}

conn.php

<?php
 require_once './config.php';

firstExample.php

<?php

require_once './db/conn.php';

when i run conn.php there is no errors.but if i run firstExample.php i got following error

Warning: require_once(./config.php): failed to open stream: No such file or directory in C:\wamp\www\testX\db\conn.php on line 2

i do some tests and able to fix the error by changing conn.php to

require_once './db/config.php';

my question is i need to add conn.php from lot of folders,sub folders.so changing like above doesn't work.for example if i run conn.php after above change then again i'm getting same error.

what i want to know is correct way of adding files.so when i add conn.php to any file config.php should be included.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
while true
  • 816
  • 1
  • 11
  • 26
  • 1
    Your answer is here, together with explanations : http://stackoverflow.com/questions/36577020/failed-to-open-stream-no-such-file-or-directory – Vic Seedoubleyew May 15 '16 at 21:39

4 Answers4

2

Look at Directory structure

you do not need to put "./"

Try:

 require_once 'config.php';

Or you can define path in CONSTANT and use it.

Vinod Kumar
  • 352
  • 3
  • 7
  • i thought './config.php' and 'config.php' both are same.but it seems that avoiding ./ fix the problem.let me test more – while true May 13 '16 at 05:55
1

You can use $_SERVER variable in PHP : $_SERVER['DOCUMENT_ROOT']

So your conn.php will change to:

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/db/config.php';

when testX is your root folder.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • There is a general troubleshooting guide here : http://stackoverflow.com/questions/36577020/failed-to-open-stream-no-such-file-or-directory – Vic Seedoubleyew May 15 '16 at 21:40
1

You can use $_SERVER['DOCUMENT_ROOT']. This is path of your document root C:\wamp\www, so including despite where the file is the link to required file is the same require_once $_SERVER['DOCUMENT_ROOT'].'/testX/db/config.php';

But due to server settings it not always shows to this directory. For more bullet proof method you should define path in your index.php or other file, that is in root directory & later use that define, eg: define('BASE_PATH', dirname(__FILE__) ); and later just use:
require_once BASE_PATH.'/testX/db/config.php;

Gvidas
  • 1,964
  • 2
  • 14
  • 21
  • There is a general checklist of solutions here : http://stackoverflow.com/questions/36577020/failed-to-open-stream-no-such-file-or-directory – Vic Seedoubleyew May 15 '16 at 21:40
1

You'll want to use the magic constant __DIR__ which will build absolute path based on the directory containing the file being executed/included:

conn.php

require_once __DIR__.'/config.php';

firstExample.php

require_once __DIR__.'/db/conn.php';

Source: http://php.net/manual/en/language.constants.predefined.php