PHP include files from different subdirectories within the root folder - php

My question is similar to PHP include file strategy needed. I have the following folder structure:
/root/pages.php
/root/articles/pages.php
/root/includes/include_files.php
/root/img/images.jpg
All pages in the "/root" and "/root/articles" directories have a "header.php" and "footer.php" file included within them, which are stored within the "/root/includes" directory.
The header and footer pages both contain images stored in the "root/img/" directory.
As suggested by:
how it`s possible to include a file (include();) from the root folder to a files from different subfolders?
How to use a PHP includes across multiple directories/sub directories with relative paths
I tried the **dirname** solution and the $_SERVER['DOCUMENT_ROOT] solution to include the header and footer in the files stored in the root directory and articles subdirectory.
However, I run into issues when I try and use either method (within the header and footer files) to link images:
<img src=" <?php echo dirname(__FILE__). '/img/image.jpg';?>">
Chrome fails to display the images and throws the following error:
locally: Not allowed to load local resource: file:///C:/root/img/image.jpg
on the server: GET http://host.com/home/public_html/root/img/image.jpg 500 (Internal Server Error)
I have checked the URL's and they appear to be correct. Having googled for solutions, I found that chrome prevents the display of files that contain it's complete file path for security reasons.
How do I get around this? or is there an alternative way to include files (including images) into files stored in any subdirectory?

#sandeep's answer is partially right. because
$_SERVER['DOCUMENT_ROOT'];
will again give back fully qualified path to the root.
<img src=" <?php echo 'http://localhost/favicon.ico';?>"/>
will return image back because now I am not giving it local path as per your problem but url of the server I am running.

for your included scripts try setting the includes_path using set_include_path
set_include_path( $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR );
Then, to include a script within your pages you can use:
include( 'script.php' );
For the images, prefix the path with a leading slash / ~ ie:
<img src='/img/image1.jpg' />
It tends to be easier to use root relative paths rather than directory relative paths so prefixing with the leading slash means a folder within the root.

This may be help you
$url = $_SERVER['DOCUMENT_ROOT'].'/img/image.jpg';
<img src="<?=$url?>">

Use ../img/image.jpg for including in files inside /root/articles.
Use img/image.jpg for including in files inside /root

Related

include_once in header breaks when an absolute path is used

I have my website on my local server (localhost - XAMPP). My website is broken up into three parts: 1)Header 2)Body and 3)Footer/Jscripts.
The header.php calls other basic files for the header section of the webpage. It works fine when I used relative paths, for example: include_once('./_css/main.css'); to call my CSS files or include_once('./_inc/metadata.php); to call my metadata for my pages.
The problem arises when I use an absolute path:
include_once('http://localhost/mywebsite.com/_css/main.css'); the same for the other files.
Why is that? This all started because I want to create subfolders because I had a general page, but now that I'm breaking it down to subpages I need a folder to contain the subpages
I was trying to include the css files and all the other resource files to the subpages, but they break using the relative paths method (./_css/main.css) being pulled from the header file located in the root directory. On the subpages, I'm using include_once('../_inc/header.php') to include the initial header.php file.
I want to avoid having to duplicate all the resource files from the root directory and adding them in the subfolder with their respective relative paths. That's why I was trying to use the absolute path method.
Any insight or clue would be appreciate as to:
Fix the 'Warning: include_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0' error when using the absolute path.
2)Sharing css files in subfolders.
Using an absolute path may be a bad idea, what if you move from localhost to a real server? You'd need to make massive changes. Changing the project structure so that you could avoid all of this might be better, or if you really want to keep things as they are, use a variable.
<?php
$include_path = "whatever/path"
include('../header.php');
?>
and in header.php
<?php
include($include_path.'/my_css.css');
?>

Pulling in files from different folder

I am working on a webpage that is located in a different folder than the root folder. I'm trying to pull in the newsletter.css file, the header.php file, and the services.jpg file. The working page is located at Root/newsletters/newsletter-2020-01.php. The header.php file is located in the Root folder, the newsletter.css is located at Root/styles/newsletter.css and lastly, the services.jpg is located at Root/images/services.jpg. The working file (Root/newsletters/newsletter-2020-01.php) isn't pulling in any of the other files. I've looked for the answer on Stackoverflow and everything is saying to use ../file.ext but this isn't working. Any advice?
<link rel="stylesheet" type="text/css" href="../styles/newsletter.css">
</head>
<?php include("../header.php");?>
<div class="background_image" style="background-image:url(../images/services.jpg)"></div>
For server level files (pulling in PHP files etc. that are done on the server, not the browser).
Use: $_SERVER['DOCUMENT_ROOT'], it's a sure thing.
https://www.php.net/manual/en/reserved.variables.server.php
$_SERVER['DOCUMENT_ROOT'] it gives you the full path of your server to the root where your HTML etc. files are stored. From there you use the path to the exact file you want.
To see it in action: <?php echo $_SERVER['DOCUMENT_ROOT'] ?>
It will make more sense.
Ex. $_SERVER['DOCUMENT_ROOT'] . '/directory/myfile.php'
As for browser level files (files accessed by the browser, .css, .js)
Use an absolute path from the root, again, a sure thing.
Ex. <script language="javascript" src="/directory/scripts/myjavascript.js"></script>
Why?
Relative paths can be broken if the file moves around. It may be relative to FileA, but FileB may be in a different location, or FileA may move, or be included in another file.
Absolute paths are a sure thing!
Consider a physical directory structure ( on Windows ) such as:
C:\wwwroot\htdocs\example
|_css
|_scripts
|_images
|_galleries
|_icons
|_banners
|_gallery
In the above typically example would be set as the document root and a call to echo $_SERVER['DOCUMENT_ROOT'] would yield c:/wwwroot/htdocs/example etc
An Absolute or Root Relative path for css, images, scripts etc would begin with a leading slash. So, to access css files you might do:
<link rel='stylesheet' href='/css/theme.css' />
or for an images
<img src='/images/banners/logo.png' />
If you start the path with ../ you are instructing the browser to fetch the resource beginning 1 folder higher ( than the current directory ) and then follow the given path. Similarly if you use ../../ that means "go up 2 levels" and begin searching from that point. There is a place for this syntax but it can be confusing and very easy to get wrong.
If you begin the path for a resource with no leading slash ( such as images/example.png ) you are instructing the browser to fetch the resource from the same level OR a sub-folder. In the given example here images/example.png suggests the image is within a sub-folder of the given path so if you are accessing the page at https://localhost/gallery/beach/index.php it would mean that there needs to be a folder structure C:\wwwroot\htdocs\example\gallery\beach\images for that to work ( unless using advanced trickery with the server config )
When it comes to including additional PHP scripts you can do so a little differently. It is not essential and in most cases it can be preferable to have the files you wish to include outside of the document root. Using the same base structure from above and having a directory for commonly included files outside of document root would mean that using a browser you could not directly open files in the includes directory - so for example: https://localhost/includes/secrets.php would fail but that file could easily be included from within PHP.
To include other PHP files you can tweak the includes_path variable using set_include_path() and thus allow PHP to include files from outwith the site root.
c:\wwwroot\htdocs\includes
You could ensure that all PHP scripts ( such as db connections and other class files ) are easily included by setting the includes_path:
set_include_path( 'c:\wwwroot\htdocs\includes' );
and then, to include a file from that directory:
require 'db.php';
You can set this to use the full path instead or you can use the ../../ style syntax also.

PHP Include relative path - clarification

I have a PHP page on my site in a sub folder called Articles.
The page is article.php.
The article.php page requires a common php page called _head.php. This provides the header for the pages.
_head.php is located in the root directory.
The /Articles directory is a subdirectory within the root.
I've included this _head.php page in article.php this way:
<?php include("../_head.php"); ?>
And this works fine.
The problem, however, is that the image elements within _head.php are located in the 'images' subdirectory (also off the root) and are referenced relative to the _head.php being in the root, like this...
<img src="images/services.gif">
So if I use _head.php for files on the root, it works great and shows all the images correctly. But when I include _head.php into a php file that is not in the root, but instead in a subdirectory like /Articles (/Articles/articles.php), the images do not show up.
Do I need to change the _head.php file in how it references the images or is there some code I'm supposed to include in articles.php when including _head.php that tells it how to use _head.php?
I'm concerned about using all absolute paths because if I have to move this site to another server this is going to cause me issues.
Mentioning what I follow not going to the hierarchical complexity,
For any PHP file that is being imported into another PHP file in root simple include/require_once (<path>).
For any file below root accessing other file anywhere within the root I use include/require_once (../<path>).
For accessing files which are outside the root, I use the absolute path of that file.
Working on few php files what I have seen using absolute path is the best thing in two ways, a) you are free from remembering the paths of different files and b) if you are using CDN or if your files are on different servers then this is very helpful. Anyways opinions may vary, this is my personal view/choice.

cant access files that have includes with relative URls

I've taken over a site that caters for client access. They all access there own folder, and in the folder the files have an include with a relative path as below.
/core - contains all the actual files
/client/file.php -
<? include "../core/file.php"; ?>
but with the growing number of clients I want to go a level deeper and separate them better...
/uk/client/file.php -
<? include "../../core/file.php"; ?>
This is fine but when the files are included, they too have there own relative includes and this is where it breaks.
There are so many files I can't easily go through them to change all the include paths so I would like to maybe do a rewrite to fake the path?
I've tried this...
RewriteRule ^uk/$ /
But that doesn't work.
Any help would be greatly appreciated
This sound like a work for __DIR__, you can check documentation here
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(FILE). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
Otherwise you can still switch all your relative paths to absolute path and avoid any problem if some file are included in others.
As side note i would reccomend to not use php short tag <?...?>, I'd rather use long tags <?php....?>

Trouble with / vs ./ vs ../ and absolute and relative paths

I have many PHP files in
/
/client/
/user/
/config/
etc...
I want all my files to include /user/codestart.php. (Lots of functions etc)
Therefore:
All files in / have include("./user/codestart.php");
All files in /user/ have include("codestart.php");
All files in /client/ have include("../user/codestart.php");
The problem is that /user/codestart.php has include("../config/config.php"); (The MySQL ID and password)
When a file in / runs, such as /index.php, it includes ./user/codestart.php.
Then /user/codestart.php includes ../config/config.php, but it cannot see it, because it thinks it is calling it from /, instead of from /user/.
If I change
include("../config/config.php") to be
include("./config/config.php")
that fixes it for / files, but breaks it for/user/ and/client/ files.
Bottom line is that when one PHP file includes another file, PHP thinks it is operating from the location of the original file, not the calling file.
I need to use relative paths, not absolute paths. Absolute paths will not work in my situation.
Is there any way to solve this?
One way to deal with this is this:
Have a central configuration file (e.g. /myproject/config/bootstrap.php
In that configuration file, define a global root for your application. E.g.
define("APP_ROOT", realpath(dirname(__FILE__)."/.."));
Include that configuration file in every PHP file. E.g.
include("../config/bootstrap.php");
Whenever you reference some other file, use
include APP_ROOT."/includes/somefile.php";
Voilá - you have a fixed point in space (APP_ROOT) and can reference everything relative to that, no matter which directory you are in.
If you want to do it this way I suggest you make a seperate file for all your includes which is in a fixed dir, the root for example.
Then you reliably include all the files from there using
include __DIR__.'path/relative/from/includefile.php'
If your php verion is lower than 5.3 you should use dirname(__FILE__) instead of __DIR__ as mentioned by RiaD
You might like this php.net page
You can use relative paths in conjuntion with dirname(__FILE__)
So in your codestart file write:
require_once dirname(__FILE__).'/../config/config.php';
You can set the path that PHP uses to look for files, so that it contains all your folders. In index.php:
$folders = implode(PATH_SEPARATOR, array('user', 'config'));
set_include_path(get_include_path().PATH_SEPARATOR.$folders);
Then you can just do:
include("codestart.php");
and:
include("config.php");
This will work for index.php and all files that index.php includes.
use absolute paths. to get path to your root directory use $_SERVER['DOCUMENT_ROOT'], ex.
include $_SERVER['DOCUMENT_ROOT'].'/user/codestart.php';
include $_SERVER['DOCUMENT_ROOT'].'/config/config.php';
It save you from absolute paths' problems.

Categories