Search code examples
phprequire

File include confusion and errors


I have the following directory structure.

public_html
    |----------app1
    |            |---------config.php
    |            |---------index.php 
    |
    |----------app2
                 |---------import.php

app1/config.php

define('ABC', 'hello');

app1/index.php

require_once 'config.php';
echo ABC;

Calling app1/index.php prints:

Hello

app2/import.php

require_once('../app1/index.php');

Calling app2/import.php prints:

Notice: Use of undefined constant ABC - assumed 'ABC' in /abs/path/public_html/app1/index.php on line 10 (line echo ABC)

ABC

Why does this happen?

How would one include in order to make it work properly?


Solution

  • You should read the documentation about include and require. Relative paths are always resolved relatively to the first called script.

    So, when you call app1/index.php, require_once('config.php') loads app1/index.php, but when you call app2/import.php, require_once('config.php')tries to load app2/config.php which does not exist.

    Advice 1: raise you error reporting level when you are coding, you will get more clues about what's wrong. In this case, include through at least a notice.

    Advice 2: avoid include if you have no good reason, use require_once which will make an fatal error when unable to load the file.