Pulling in files from different folder - php

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.

Related

Linking CSS file with PHP throgh all folders

INTRO
I am new to php. I love that it allows me to change one header.php file and it updates all over the site.
IF all - index.php, header.php, style.css, article.php, homework.php files are in the ROOT folder, everything works like magic, I like it. I use:
<?php include_once "header.php"; ?>
at the top of index.php, article.php and homework.php and the header appears.
to load css a regular =
<link href="style.css" rel="stylesheet" type="text/css">
is enough to have in my header.php file, because all the files are in the same directory.
MY PROBLEM
When the amount of articles becomes too large and I decide I want to put those articles in different folders, that is when stuff gets confusing and I would like to know a proper way to solve it.
New website folder structure
C:\xampp\htdocs\articles\homework.php
C:\xampp\htdocs\views\header.php and style.css
C:\xampp\htdocs\index.php
C:\xampp\htdocs\articles.php
Now please help me how to make homework.php file to load the css from the header.php? I manage to load the header itself with
<?php include_once "..\views\header.php";?>
BUT the css file doesn't load for some reason.
I read something about "basenames", "site roots", but don't know how to properly set them up.
The perfect scenario
The perfect scenario would be if I could have a basename variable that I can change, so when I make my server live I can just change the basename to the appropriate new server directory and because all the header.php and other blog files were linked to that basename, everything would change automatically. I have done too many manual directory rewriting to do it once again, please tell me a way to automate it :)
Thank you a lot!
p.s!!!!!! Before I even post this question I realized that the header.php is trying to load views/style.css, which doesn't make sense, because the style.css file is in the same folder as header.php now.. Somehow basenames, site roots are a must here I believe...
You can specify relative paths such as ../css - means up one folder then look in css folder or ../../ - means up 2 levels then look in css folder.
../../main/css/style.css - would mean up 2 levels then look in main/css for the file style.css.
The problem with using / or ../ etc is that if you decide to change the location of the resource you still have to change all your paths. Using a var you can simply change it to reflect the new location.
with PHP you can also getcwd() and dirname() and realpath() to get a string representing a location, you can then set a base variable for your files and 'path' down from it.
This way you can use the same variable to locate a file rather than different relative paths depending on the level of the file calling it.
DIRECTORY_SEPARATOR is also useful for avoiding errors between / and \ with linux and windows OS. However I believe Windows and Linux will both resolve /
Personally I like to set path locations to commonly used files such as /includes in config.php then I can use that setting from anywhere
In summary you are just either discovering a path using PHP or setting a path as a variable
$path = 'c:/htdocs/mysite/includes/';
then using the variable as part of the path name when you access the file
$_SERVER['DOCUMENT_ROOT']
can also be useful to identify your site home folder

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.

PHP include files from different subdirectories within the root folder

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

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....?>

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