13

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";
3
  • I think you need to just step it out a level, ie. ../../blog.php assuming that blog.php is not in the blog folder. Commented Dec 16, 2012 at 5:33
  • I don't think that would work. blog.php is in the blog directory. Commented Dec 16, 2012 at 5:35
  • Ahh your notation of directory structure was confusing to me :-) Commented Dec 16, 2012 at 21:47

4 Answers 4

43

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This worked. Thanks! Though I have no idea why do I have to do this. The instructor gets away with require "../blog.php"; without any problem. Is it because of OS differences? He's on Mac, and I am on Windows.
I'm actually not entirely sure - I believe it has to do with the current working directory not always matching the script's directory.
@Rafay: its a bad practice anyway. You should always calculate the absolute path and then require/include.
3

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

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

Comments

2

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";

Comments

-3

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.

3 Comments

That's why you have the include_path directive in the php.ini.
include_path doesn't apply for things like file_exists though ;)
and one file operation per php file with no real use. Consider using PSR-0 or using DIR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.