← All field notes

engineering / October 20, 2011

Solution: Using Include or Require in PHP but Can't Find File

The situation is you are trying to use include or require to load a file from a folder in your site, when the file you are calling include or require from is inside a different folder in the site and…

Editorial blueprint illustration for Solution: Using Include or Require in PHP but Can't Find File
Original Esotech field note / illustration generated for this archive
ARCHIVE IMAGE / SOURCE UNAVAILABLEphp-logoThe original file was referenced by this article but was not present in the export. The situation is you are trying to use include or require to load a file from a folder in your site, when the file you are calling include or require from is inside a different folder in the site and NOT the document root. The issue is, when you use include outside of your document root, it considers that folder as the document root, so you are forced to give it the real root directory of your website on the server. Your File:
website.com/directory/script.php
Your Code in that file:
require_once( "/directory2/filename.php");
or
include_once( "/directory2/filename.php");
If properly configured, you can use this PHP Server Key/Variable.
$_SERVER["DOCUMENT_ROOT"]
So a good Example would be the following:
include_once( $_SERVER["DOCUMENT_ROOT"] . "/directory2/filename.php");
or
include_once( $_SERVER["DOCUMENT_ROOT"] . "/directory2/filename.php");
In the case that directory is the folder just after the root of your site.