Trying to use one include file on multiple subdirectories - php

I have a header.php that I'd like to include on all pages of the script I'm making. It has the nav bar and header.php includes auth.php which is some basic authentication you'd expect a header page to have.
The problem I am having is relative paths vs absolute paths. My directory structure looks like the below
/root
-index.php (contains include ('inc/header.php');)
-auth.php
/inc
-header.php (contains include ('auth.php);)
Now this works perfectly well. However when I add some functionality and get the following directory structure things start to break
/root
-index.php (contains include ('inc/header.php');)
-auth.php
/inc
-header.php (contains include ('auth.php);)
/newFunctionality
-newStuff.php (contains include('../inc/header.php') but breaks because of relative paths fidning auth.php
I've played around with things like $fullPath = dirname(__FILE__); and I believe that this is most likely how I'm going to fix this problem.
I've seen very similar questions with answer like this. I'd like for this script to be independent of the index however. Is there a way to make this happen?

I've alway found it easiest to set a base path constant and include my top level scripts base on that
define ('APP_ROOT', '/path/to/application/root');
include(APP_ROOT."/libs/MyFile.php");
Normally I would put this (along with any other site constants) in an include file and include it relative to the either the document root
include($_SERVER["DOCUMENT_ROOT"]."/config/site.php");
or specify the location of the file in my .htaccess
SetEnv APP_CONFIG /path/to/application/config.php
then in php
include ($_SERVER["APP_CONFIG"]);

Related

include() and require_once() Issue

I have this situation:
/
index.php
/init (folder)
init.php (of course inside this file i use require_once for db/function/and whatever you want to put inside)
/layout_parts (folder)
header.php (and others common parts are inside this folder)
/my_space (folder inside layout parts)
my_file.php
another_file.php
/your_space (folder inside layout parts)
your_file.php
another_file.php
/third_space (folder inside layout parts)
third_file.php
another_file.php
For the index i have no problem it all works fine, but if i include header.php in one of the subfolder files my require_once(init/init.php); that is on the top of header.php won't work.
(Warning message says no such file in the directory (OF COURSE THE FILE EXIST) and it write down the subfolder directory that is not the path i expected).
I tried echo $SERVER['DOCUMENT_ROOT]; to see the whole path, echo __DIR__; to see wich is the right path to the directory, no way out.
I know is such a dummy question but if some kind heart could help me it would be great. Thanks :)
The best way to handle this would be to use absolute paths instead of relative ones. When you use relative paths, you have to worry each time about how many levels deep you are and then have that many ../ etc. This is messy and difficult to manage, for eg, if you move a file to a different location, you have to update the includes again, based on where you are now. This is why absolute paths are helpful.
So create something like this:
$appRoot = "/path/to/root/folder/";
This is the path where the index.php file is located. It is the "application root", if you will.
Now, in ANY file where you want to include init.php add the following line:
include_once($appRoot."init/init.php");
Ideally the $appRoot should be created in a global config located in root. If you do not have a structure where a univeral config can be added, it can still be messy and you might need to add absolute paths into individual files (which is not a good idea)

how to include from differing directory paths and depth

i am trying to include the same connect.php file as a part of the nav.php file throughout multiple different directories and directory depth's with a generic 'dynamic' substitute for the include path back to the connect.php file in the website root folder eg.
www.mywebsite.com/shop/shoes/sandals/index.php
and
www.mywebsite.com/shop/shoes/sandals/index.php
etc.
with the connect.php file being located in the root directory
www.mywebsite.com/connect.php
the code I am currently using in the nav.php (which is included in all pages and directories that are accessible by users)is as follows.
<?php
include '../../connect.php';
?>
however this will obviously not work in directory paths like
www.mywebsite.com/shop/shoes/sandals/index.php
I have no previous experience making a single connect.php file accessible by multiple directory paths using an absolute path with php.
however some guidance on this matter would be extremely helpful.
Thanks
You could try using something like
include $_SERVER['DOCUMENT_ROOT'] . "/connect.php";
To continue reading...
Hope this helps!

Configure PHPStorm to take into account relative paths for included files?

I've just started with PHPStorm and I'm encountering an issue.
So when including a file, if you then include another file within that the path isn't understood correctly.
e.g.
Folder structure:
root/ Contains index.php
view/ Contains view.php
lib/ Contains functions.php
So if I include view.php in index.php:
index.php:
include('view/view.php');
or
require('view/view.php');
When this code is run, anything within view.php is included in index.php, so any files included in view.php are relative to the root directory.
view.php:
include('lib/functions.php');
But PHPStorm thinks they're relative to the view directory.
view.php:
include('../lib/functions.php');
Which in this situation they aren't.
This issue is also occurring for things like: Link
How do I configure PHPStorm to pick up this situation? I'd assumed it would work this out automatically, but currently it isn't.
Specific example:
private/
privatefile.php
public/
index.php
views/view1.php //Included in index.php
views/view2.php //Included in index.php
Would 'public' be the resource root in this situation if I want to include privatefile.php in view1.php?
So the include in view1.php would look like: include('../private/privatefile.php');
Marking folder as "Resources root" will only help for HTML/CSS (e.g. links to images/css files/js files and alike) -- it will NOT affect actual PHP includes in any way.
In your public/index.php (which is your entry-point script -- all requests will go trough it) define some constants, e.g.
define('DIR_WEB', __DIR__); // points to your public
define('DIR_APP', dirname(__DIR__)); // points to your project root
and use them in your include/require statements, e.g.
include (DIR_WEB . '/views/view1.php');
include (DIR_APP . '/private/privatefile.php');
This way you ALWAYS referring to the same file (using absolute path) regardless where that file is located.
You have to remember one thing: PhpStorm only performs static analysis -- it cannot do the same as PHP interpreter does (which works during run-time). Therefore IDE checks your include statements relative to either project/module root or actual script where it is used.
Using the above will satisfy both PhpStorm as well as PHP itself (you will be using full path, so no need to search for include files -- which is a bit faster -- can make some difference on very busy sites with lots of includes). Plus it's safer -- as you always refer to specific file so there is no chance that PHP will load similarly named file from another location by mistake.
Go to Settings->Languages & Frameworks->PHP and add your appropriate dir as "include path". The inspections will show ok then. The only disadvantage is that this is global settings not per project.

PHP: require doesn't work as it should

I have a directory root:
index.php
includes/
template.php
testfile.php
phpFiles/
processInput.php
testfile.php
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
processInput.php:
require_once("testfile.php")
require_once("../testfile.php")
This code will work when you run index.php, of course it will not work when you run template.php.
As you can see, index.php includes template.php like normal. But in template.php, you have to include like if you are in the directory that index.php is in. But then, in processInput.php, you include as if you are in the directory that processInput.php is in.
Why is this happening, and how can I fix it so that the include path is always the directory of the file that the require is done in? The second included file have the same include path as the requested file, but the next one does not.
Thanks for your help!
EDIT: The strange thing is that I've included classes in a class folder. And it included other files as it is supposed to, even though the paths are relative. WHY does this happen, and how can I fix it?
VERY IMPORTANT EDIT: I just realized that all this is because in my example, the inclusion in includes/phpFiles/processInput.php includes a file in the same directory: require_once("file in same dir.php"); This is the reason. If you are including a file with out specifying anything more than the filename, the include_path is actually the dir where the file the require is written in is in. Can anyone confirm this?
Use an absolute path.
require_once($_SERVER['DOCUMENT_ROOT']."/includes/phpFiles/processInput.php");
Use a similar form for all your required files and they will work no matter where you are.
You can do this in a few ways, amongst others:
Use set_include_path to control the directories from where to perform require() calls.
Define a common absolute base path in a constant that you define in index.php and use that in every require() statement (e.g. require(BASEPATH . '/includes/template.php')).
Use relative paths everywhere and leverage dirname(__FILE__) or __DIR__ to turn them into absolute paths. For instance: require(__DIR__ . '/phpFiles/processInput.php');
By default, the current working directory is used in the include path; you can verify this by inspecting the output of get_include_path(). However, this is not relative to where the include() is made from; it's relative to the main executing script.
You're using relative paths. You need to use absolute paths: $_SERVER['DOCUMENT_ROOT'].
When you include/require, you are basically temporarily moving all code from one file, to another.
so if file1.php (which is located in root) contains:
require("folder/file.php");
and you include file1.php in file2.php (which is in a different location (say folder directory for example):
file2.php:
require("../file1.php");
Now all of file1.php code is in file2.php. So file2.php will look like this:
require("../file1.php");
require("folder/file.php");//but because file2.php is already in the `folder` directory, this path does not exist...
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
Your directory structure is off. The file inclusion is being seen from the file you're using it from. So, "template.php" is looking for an "includes/" folder in its current folder (/includes/).
As others are saying, use absolute paths, which will make sure you're always going at it from the file system root, or use:
require_once("phpFiles/processInput.php")
In your template.php file (which is far more likely to break if you ever move things around, which is why others all recommend using absolute paths from the file system root).
BTW, if you're using "index.php" as some kind of framework system, you can consider defining a variable that stores the address of common files such as:
define('APPLICATION_PATH', realpath(dirname(__FILE__));
define('PHPFILES_PATH', APPLICAITON_PATH . '/includes/phpFiles/');

PHP broken relative links in nested directories

I'm sure I'm missing some simple explanation, but I want to confirm - so assume I know very little.
I have a directory structure like so (for the time being) of:
My main site (localhost/project/ on my testing server, and C:/xampp/htdocs/project on my HDD) with these files and folders:
Root
graphics
variousgraphics.png
support
stylesheet.css
templates
header.php
footer.php
initialize.php
you
default.php
index.php
anotherfile.php
Up until I created the folder 'you' everything was fine, i.e. I included the initialize file for index.php as <?php include(templates/initialize.php) ?>
But when I decide to include initialize.php using the above method for the default.php file (inside 'you'), it errored out with Warning: include(templates/initialize.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\photoquilt\you\default.php
So naturally I appended ../ to create <?php include(../templates/initialize.php) ?> but then of course that didn't work because the files referenced inside initialize.php weren't appended in the same way, and so I get to here.
It's worth noting for me, an echo of $_SERVER['document_root'] leads to C:/xampp/htdocs
So in summary:
Is there any way to make sure all the link/paths work correctly irrespective of where the originating path was from?
In default.php you can define a constant like
define('ROOT_PATH', dirname(__DIR__));
or for php versions prior to 5.3.0
define('ROOT_PATH', dirname(dirname(__FILE__)));
and then use ROOT_PATH in all scripts to build the the file paths.
see
- http://docs.php.net/language.constants.predefined
- http://docs.php.net/dirname
There are a couple problems here as far as I can tell: the server-sided and the client-sided.
As for the PHP goes, you are doing it fine. Referencing the file by its relative path (../templates/initialize.php) is the way to go. There's another way of achieving the same, though I wouldn't recommend it: editing the include_path to add the root directory of your project. You can do it in an .htaccess located in the root directory, ie:
php_value include_path ".:/path/to/your/project:/usr/local/lib/php"
For the HTML part (images not loading, stylesheets not found), you can set a base href:
<base href="http://path.to.your/in-server/" />
The base href should point the root of your directory. All the images, stylesheets, etc in HTML must then be fixed to use relative URIs from the root of the project (graphics/variousgraphics.png).

Categories