Reputation: 816
I have three php files. The "upper" file is a webpage (let's call it Sample.php). At the top of the page it does this:
<body>
<?php include("../Top.php"); ?>
//Webpage content
</body>
The Top.php file is a file with the menu and banner stored, for easy changing. The Top.php file has a line as such:
<?php include("ConnectToDB.php"); ?>
ConnectToDB.php is a file with some php code to connect to a database.
Here, the file system is ordered like so:
When I access Sample.php I get an error in the include("ConnectToDB.php");
inside the include("../Top.php");
statement. but if I have the file OtherSample
with the include("Top.php");
statement I will get no error and both Top.php and ConnectToDB.php work perfectly. What is the problem?
Upvotes: 1
Views: 1166
Reputation: 1
I encountered the same problem. unfortunately,Samson's answer can't solve the problem for me. You could try this one. It works fine for me. Adding a file exist check then add the correct path in your Top.php like this
<?php
if (file_exists("ConnectToDB.php")) {
include_once("ConnectToDB.php");
}elseif(file_exists("../ConnectToDB.php")){
include_once("../ConnectToDB.php");
}
?>
then you can access the correct path.
Upvotes: 0
Reputation: 2821
The "include" statements actually ports the code into your page. So keep in mind that include("ConnectToDB.php")
is executed from Sample.php, therefore the path is wrong.
The correct line of code would be: include("../RootFolder/ConnectToDB.php")
where ..
represent the whole dir structure after "localhost/"
or whatever you are using.
Upvotes: 3
Reputation: 42654
You could use:
include_once($_SERVER['DOCUMENT_ROOT'].'/RootFolder/whatever.php');
to include files, this way you always have an absolute path for the include and it isn't dependent from where it is called.
Upvotes: 5
Reputation: 7380
The path is wrong, by calling Sample.php all path belong to the base where the Sample.php is located. PHP searches for ConnectToDB in the wrong folder... Try ../ConnectToDB.php, as from the Sample.php file, this file i one folder above...
Better solution, use an absolute path!
Upvotes: 1