Lemures
Lemures

Reputation: 482

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?

Upvotes: 1

Views: 51

Answers (3)

user6299088
user6299088

Reputation:

Use

require_once __DIR__ . '/config.php';

instead of require_once 'config.php';

Refrence : PHP file paths and magic constants

Upvotes: 2

cn0047
cn0047

Reputation: 17061

The problem is that you run script php app2/import.php from folder public_html not from public_html/app2.
If you do this:

cd app2 && php import.php

All will work!

Your example with require_once 'config.php'; in app1/index.php works because files index.php and config.php placed in same directory.
But app2/import.php placed in another directory from app1/config.php hence you can't use this approach in this case.

With purpose avoid this mess with relative paths you have to use constant __DIR__ in your paths in import.php, like this :

<?php
require_once(__DIR__ . '/../app1/index.php');

and now you can run this script from public_html directory.

Upvotes: 1

St&#233;phane Mourey
St&#233;phane Mourey

Reputation: 145

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.

Upvotes: 2

Related Questions