Reputation:
I know this isn't the right way to use stackoverflow, but i just have to have a quick answer to my problem
this is the folder hierarchy
login (folder)
-- login.php
php (folder)
-- connection.php
index.php
in login.php i use include_once("../php/connection.php")
in index.php i use include_once("login/login.php")
when i run index.php i get the following issues
Warning: include_once(../php/connection.php): failed to open stream: No such file or directory in /.../public_html/plog/login/login.php on line 3
thank you in advance for your help :)
Upvotes: 0
Views: 954
Reputation: 15391
You are closer to the best answer, but a better pattern is this:
You create a bootstrap script and place it in a known location. For this to work all that is important is that every script needs to require_once() the bootstrap file relative to that script.
Most frameworks use a front controller pattern which is a typical entrypoint to MVC frameworks, but even if that is too complex for you at this point, this technique still works so long as you always require_once('../somedir/bootstrap.php');
The bootstrap.php script is a good place for any configuration settings, reading environment variables, setting constants etc.
Prominently at the start you want to have something like this:
if (!defined('ABSPATH')) {
define('ABSPATH', dirname(__FILE__) . '/');
}
So now, all that is important is that you understand the relationship any other files may have to the directory that bootstrap.php is in. Let's say for example, you put it in the login.php directory.
Then your require_once() would be:
require_once(ABSPATH . login.php);
For connection it would be:
require_once(ABSPATH . '../php/connection.php');
I highly recommend require_once over include_once, if your system is effectively non-functional without the included file, as it probably would be if you can't connect to the database on login. require_once will cause a runtime error, whereas include_once just continues on it's merry way whether or not it could actually find and include the file.
Not a huge fan of your directory naming to be honest. A directory called /php? What does that tell you? Isn't this all php code?
People have put a lot of thought into good structures, and then there is the PSR efforts, composer etc. Take a look at this for a better plan.
Upvotes: 1
Reputation:
I did some research and found that the best way to do this, without having to declare any constants was the following:
in login.php i include connection.php this way include_once( substr(__DIR__, 0, strrpos(__DIR__, "/") + 1 ) . "php/connection.php")
;
so this would fix the entire problem. I don't have to define anything. Now i can copy this subfolder almost everywhere without having to change anything.
Upvotes: 0
Reputation: 3030
I update the code so with the constant BASE_URL you will define the root so you can use it from other site
<?php
define('BASE_URL', 'http://example.com');
include(BASE_URL."/php/connection.php");
?>
Upvotes: 0