When attempting to link from the root directory in my PHP file, I am unable to load the file. It works fine unless I add the file path as absolute, like so:
<link href="/supportfiles/subheader/css/css.css" rel="stylesheet" type="text/css">
<div id="subheadingContainer">
<div id="allContentContainer">
<?php
if (count($loggedIn["directReports"]) != 0 ) {
require("/supportfiles/subheader/itemshtml/inbox.php");
} else {
require("/supportfiles/subheader/itemshtml/myrequests.php");
}
?>
</div>
</div>
Any idea why it works fine if I ../ but not if I hard code it? This is a support heading file, so im using it across multiple levels in directories and I think it should be hard coded from the root.
When you use absolute paths in PHP, / refers to the root of your file system, not the root of your web application, this means that if you want to use absolute path you have to use the path as if you accessed from your file manager, not from the browser.
For example lets say that you are working on linux with apache and that the root directory of your apache server is /var/www/ then you would have to put:
require("/var/www/supportfiles/subheader/itemshtml/inbox.php");
if you are unsure of your document root you can use the PHP's $_SERVER['DOCUMENT_ROOT']. so in your case just put $_SERVER['DOCUMENT_ROOT'] before any absolute path and this must work just fine. so for example:
require $_SERVER['DOCUMENT_ROOT'] . '/supportfiles/subheader/itemshtml/inbox.php';
Related
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.
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
So I have some php files that I'm trying to include with no luck.
I have the root directory, and off that I have a directory called aboutus. In the aboutus directory, I'm trying to include a css file from the root. So I use this code:
include $_SERVER['DOCUMENT_ROOT'] . "/meta-head.php";
The include works fine, but in the meta-head.php there are some calls to files, one of which is:
<script src="_assets/js/navbar.js"></script>
The problem is that it's trying to access this from root/aboutus/_assets/js/navbar.js (which doesn't exist), when I want it to acccess it at root/_assets/js/navbar.js.
What am I doing wrong so that it won't access the file relative to the root?
Thank you!
use absolute path or use this:
<script src="/_assets/js/navbar.js"></script>
Most of my website is in my root directory. And In that directory there is "css", "functions", "images" folder. Everything works fine when I include php files within index.php or any other root file. It includes it fine and executes it fine.
But problem occurres when I made folder "blog". So this is totally new and separate root folder with CMS and its own "root" files. And I try to include css from main root directory or some php files from "functions" folder in main root directory, Everything breaks down. I know I have to include it as ../functions/myfile.com. But this files includes some other files so it just wont work properly and won't be able to include other files properly.
Is there any idea how to fix this problem?
You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:
User-agent: *
Disallow: /blog/
Other possibilities:
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}
If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?
If this is the case, you just have to follow the trail the right way.
Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.
i had the same issue and found a code on https://css-tricks.com/php-include-from-root/ that fixed it
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
None of the above answers fixed this issue for me.
I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.
I like to work on websites locally before uploading to my host. I use PHP/MYSQL servers in an XAMPP install.
I have multiple directories in XAMPP htdocs directory (one for each project). Each project usually has at least:
header.php
index.php
footer.php
styles/stylesheet.css
This worked fine until recently.
I am now working on a more extensive file/directory structure. Now, when /about/index.php calls header.php, the path to the stylesheet directory doesn't point in the right direction. Image paths no longer point in the right place either since they are all relative paths.
I tried pointing everything to the home directory first using a "/" at the beginning of every path, but in XAMPP the home directory now refers to localhost, instead of the directory for the particular project.
What is the solution? Is there a better way to be working on projects locally so I can upload to my web host simply, using all relative paths and not having to change them for live and dev versions of the website?
The simplest solution as answered by #Vladimir Dimitrov in this thread goes as following (I will just copy it here):
The easiest way is to create separate virtual host for each site folder in /htdocs So you will access the http:// mysite.local instead of http:// localhost/mysite
There are two things to do: 1. edit C:\xampp\apache\conf\extra\httpd-vhosts.conf (by default) adding something like:
<VirtualHost *:80>
ServerName mysite.local
DocumentRoot C:/XAMPP/htdocs/mysite
</VirtualHost>
edit c:\windows\system32\drivers\etc\hosts adding
127.0.0.1 mysite.local
restart xampp and try http://mysite.local
Possibly this helps you?
You have to edit some config to reference each site to a base-link.
creating-multiple-sites-on-a-local-web-server
You could try this:
create a common configuration file
define a BASE_URL constant to your home directory (e.g. http://localhost/my_project/)
in your templates use all your links and references with BASE_URL
When you will deploy, you will need to change only one file.
You could also set a BASE_PATH constant to your directory (e.g. c:/xampp/htdocs/my_project). This might be useful when trying to include scripts from various sub-directories, without "guessing" the local path. (e.g. include BASE_PATH . 'templates/my_template.php')
Try including them using `DOCUMENT_ROOT for your PHP files, ie:
include($_SERVER['DOCUMENT_ROOT']."folder/header.php");
This assumes, when looking in the browser, header.php can be ound by going http://127.0.0.1/folder/header.php
For other files, such as CSS, Javascript you could define the location as follows:
define("SCRIPTS_URL", "http://127.0.0.1/_scripts/");
Include the above in your header.php file, and make sure you include header.php before calling the actual html header, eg:
<?php
include($_SERVER['DOCUMENT_ROOT']."folder/header.php");
?>
<html>
<link rel="stylesheet" type="text/css" href="<?php echo SCRIPTS_URL; ?>stylesheet.css">
... etc etc ...
You can further combine define and build up directory parts, for example:
$project = "project_x";
include($_SERVER['DOCUMENT_ROOT'].$project."/header.php");
define("SCRIPTS_URL", "http://127.0.0.1/".$project."/_scripts/");
If you do it like above, then you only need to change the project variable, if you see...
Update
The below would be index.php:
<?php
// Make the header relative to index.php (as we don't know the project) - assume header is located at /_template/header.php and this file is located at /index.php [if, in future you have /content/index.php - then the below would be ../_template/header.php, etc]
if(file_exists("_template/header.php")){
include_once("_template/header.php");
} else {
die('Fatal error - no header found');
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>styles/stylesheet.css">
</head>
<body>
// Content goes here
</body>
</html>
<?php
if(file_exists(ROOTPATH."_template/footer.php")){
include_once(ROOTPATH."_template/footer.php");
}
?>
And header.php:
<?php
define("PROJECT_NAME", "project_x");
define("ROOTPATH", $_SERVER['DOCUMENT_ROOT'].PROJECT_NAME."/");
define("BASE_URL", "http://".$_SERVER['SERVER_NAME']."/".PROJECT_NAME."/"); // $_SERVER['SERVER_NAME'] automatically puts 'localhost' or the domain name in automatically
?>
As you can see - everything is defined in this header file and when it is included on index.php - index.php can access those definitions, as can any other file that is included after the definition has been made (note that you cannot overwrite a definition and cannot define the same definition twice.
I solve this problem by defining some constants:
# index.php
# handles pretty much everything for the site
define( 'DS', DIRECTORY_SEPARATOR );
define( 'ROOT', dirname(__file__) );
define( 'HOST', 'http://' . $_SERVER['HTTP_HOST'] . dirname( $_SERVER['PHP_SELF'] ) );
Then, for includes, I do something like this:
include ROOT . DS . 'directory' . DS . 'file_i_want.php';
For CSS and whatnot, it may be easier to just set the base URL in the markup.