0

I have a home.php file which references fileA using php require command which is in the same folder i.e. localhost. the code is:

<?php // /localhost/home.php
require ('/fileA.php');
?>

fileA references another file in its code fileB. so far its workin properly when i access fileC.php i reference fileA using

<?php // /localhost/A/B/fileC.php
require ('../../fileA.php');
?>

the code is able to acquire fileA but only works properly when fileB is in the same folder as fileC else produces a 404 error.I am not able to understand why is this happening since fileB is called by fileA.

thanks.

1 Answer 1

2

When using relative file paths, keep in mind that they are relative to your current working directory, not to file that performs inclusion. current working directory is set automatically on the first request (A/B in your case).

Some simple solutions: always use dirname(__FILE__) before including file, this way it be relative to the file the is in:

<?php 
require(dirname(__FILE__)."/FileA.php"); 
require(dirname(__FILE__)."/../../FileB.php"); 
Sign up to request clarification or add additional context in comments.

5 Comments

By dirname(__FILE__), you mean __DIR__? :)
Yes, but __DIR__ is only avaliable since php 5.3, dirname also works for older php installations.
but i dont have to call fileB from fileC , fileB is called from fileA
So by your argument the folder that has fileA must then be set as current working directory since fileA is called perfectly.
FileA is included, because it is referenced from current working directory. If in your FileA you have require('FileB'), than php will search for FileB in A/B (where FileC resides) sice it is current working directory. Of course you can also change current working directory, but this often leads to more confusion with paths.

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.