Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you know the correct path to use in a PHP require_once() statement

Tags:

php

As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:

require_once("config.php");

or sometimes

require_once("../config.php");

or even

require_once("../../config.php");

But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require_once() call is made because I can have two files in the same directory that have different paths for the config.php.

How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require_once() statement;

What's the secret? From where is that path evaluated?

Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.

like image 952
dl__ Avatar asked Nov 05 '08 21:11

dl__


1 Answers

I like to do this:

require_once(dirname(__FILE__)."/../_include/header.inc");

That way your paths can always be relative to the current file location.

like image 59
bobwienholt Avatar answered Sep 29 '22 00:09

bobwienholt