ajk4550
ajk4550

Reputation: 741

PHP file inclusion on a required file

Here is an example directory structure:

-Root
    index.php
    -forms
        -form.php
    -include
        -include.php

In my index.php I am requiring the form.php

require_once('forms/form.php');

in my form.php I am requiring the include.php file. Which of the following is correct:

require_once('../include/include.php');
require_once('include/include.php');

My confusion comes from the idea that the form is being rendered in the index file, so would the files the form include need to be relative from the index (since that is where its rendered) or would it need to be relative to itself regardless of where it is rendered.

Upvotes: 0

Views: 70

Answers (2)

Rizier123
Rizier123

Reputation: 59681

You can use the magic constant __DIR__, so you don't have to think about this, e.g.

require_once(__DIR__ . '../include/include.php');

Upvotes: 7

n-dru
n-dru

Reputation: 9420

Correct is

require_once('include/include.php');

but it is beter to use absolute path:

require_once(__DIR__.'/include/include.php');

__DIR__ works from PHP 5.3.0 up. In earler versions its equivalent was dirname(__FILE__)

Upvotes: 2

Related Questions