Search code examples
phpincludexampppearrequire-once

PHP throws a Fatal Error when trying to include/require a script that includes/requires another script


That's basically it, as far as I can tell. I can include or require_once a script that has no includes/require_once, but if it does, then PHP throws me this error:

Warning: require_once(../constants/constants.php) [function.require-once]: failed to open stream: No such file or directory in C:\Home\Workspace\PHP\DD\src\log\test.php on line 7

Fatal error: require_once() [function.require]: Failed opening required '../constants/constants.php' (include_path='.;C:\Program Files\Xampp 1.7.7\php\PEAR') in C:\Home\Workspace\PHP\DD\src\log\test.php on line 7

The path is correct. I fear I may have messed up some configuration file of the Apache Webserver (I created a .htaccess file to use mod_rewrite in order to create some better URLs). The .htaccess file content is just this:

Options +FollowSymLinks

RewriteEngine on

RewriteRule !.(gif|jpg|png|css)$ index.php

My apache document root is "C:/Home/Workspace/PHP"


UPDATE: I found out that using an absolute path works, like this:

require_once $_SERVER['DOCUMENT_ROOT']."/DD/src/constants/constants.php";

I guess I'll just not use relative paths, then.


Solution

  • The reason for this is that the relative paths are from the file with the first require/include. For example, if I had a group of files that looked like this:

    |--bar
    |   |--foo
    |   |   |--foo.php
    |   |--bar.php
    |--test.php
    

    if test.php had

    require("./bar/bar.php")
    

    and bar.php had

    require("./foo/foo.php")
    

    Then this would fail because the relative URLs must be relative to the working directory (the top file that called the require/include). If I changed bar.php to require("./bar/foo/foo.php") then the program would complete successfully. The best way to make sure this does not happen is to, as Basti stated, not use relative URLs. It is generally advisable to use various functions like dirname(__FILE__) to construct the URLs.

    One last thing, the rewrite rule in the .htaccess file won't do anything, it only manipulates client side URLs. I hope that clears up any confusions.