Rafay
Rafay

Reputation: 24285

PHP - Relative paths "require"

My directory structure looks like this:

blog -> admin -> index.php
blog.php
db.php
functions.php

I have been trying to include (require, really) blog.php in the admin/index.php, but facing lots of errors. I'm following a PHP course, and the instructor does the same thing successfully.

admin/index.php:

require "../blog.php";

which, in turn, requires two more files in its directory.

require "db.php";
require "functions.php";

Upvotes: 13

Views: 37054

Answers (4)

Sam Dufel
Sam Dufel

Reputation: 17608

If you find that relative include paths aren't working as expected, a quick fix is to prepend __DIR__ to the front of the path you're trying to include.

require __DIR__ . "/../blog.php";

It's reasonably clean, and you don't need to modify the include path or working directory.

Upvotes: 43

Andy Lester
Andy Lester

Reputation: 93815

You need to set the include_path in your php.ini.

If you want to set it at run-time, use set_include_path().

Upvotes: 3

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

If you are including this files db.php and functions.php in index.php then you have to write this code

require "../db.php";
require "../functions.php";

OR if you are including this files in blog.php then write this code

require "db.php";
require "functions.php";

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

I like to start my files with chdir($_SERVER['DOCUMENT_ROOT']). This allows me to get a nice and logical base path for all my includes.

Upvotes: -3

Related Questions