making relative path for include files - php

I wish to use header (includes css, js and images) and footer files located in a folder called /template. These files then get included in every file down the directory for example:
/template/header.php + footer.php
/home/index.php
/products/products.php
/products/hardware/types/hardware.php
/css
/js
/images
When i use:
include (__DIR__ . "/../template/header.php");
The file is included (although i need to change each file and ad more "/../" the further down the directory i go) but all the css, js and images are broken.
here is my header (located in header.php, one of the included files):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="icon" type="image/gif" href="images/favicon.ico">
<link rel="stylesheet" type="text/css" href="../css/layout.css"/>
<link rel="stylesheet" type="text/css" href="../css/slider.css"/>
<link rel='stylesheet' type='text/css' href='../css/menus.css'/>
<link rel='stylesheet' type='text/css' href='../css/forms.css'/>
<link rel="stylesheet" href="css/jquery-ui.css" type="text/css" media="all"/>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.elastic.source.js"></script>
<script type="text/javascript" src="../js/control.js"></script>
<title>APEC Energy - <?php echo($PageTitle);?> </title>
</head>
I am now trying to use a config file (which is hard to get working and still doesnt for me).
config.php (placed in root folder)(Do i need to place more information in the array, file path or directory path? if so how?):
<?php
$paths = array(
"root" => "./",
"controller" => "controller",
"stylesheets" => "css",
"images" => array(...),
"javascript" => array(...),
);
$projectName = "/";
function fInc($filePath){
global $projectName;
return '//'.$_SERVER['HTTP_HOST'].'/'.$projectName.'/'.$filePath;
}
?>
and in each .php file calling for the including file im using:
<?php
$rootDir = $_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1]);
require_once($paths['helper']['html']."template/header.php");
?>
When i use var_dump($paths), it prints out "NULL"
but just get a blank screen now?
thank you

I always included a config.php in the first line of each php:
require_once($_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1])."/config.php");
This code should always find the root directory, and then include the config.php file.
Note that you can put this file anywhere you want - it will always find it's location on its own. If you move the file to another directory subsequently, you don't have to change anything.
This config file then defines the paths to all subdirectories and other important files, relative to the root directory:
$paths = array(
"root" => "",
"controller" => "controller",
"stylesheets" => "css",
"images" => array(
"icons" => "img/icons",
"controls" => "img/controls"
),
"javascript" => array(...),
...
);
This array means, that the root folder (your public_html) contains the directories "controller", "stylesheets", images" and so on. Images are either placed within "img/icons" or "img/controls".
All other files are included so:
require_once($paths['helper']['html']."/form.php");
This can be very useful, because it allows you to restructure your complete directory layout, and you only need to update your config.php.
And, last but not least, the config also contains a function like this:
$projectName = "YourProjectFolderName";
function fInc($filePath){
global $projectName;
return '//'.$_SERVER['HTTP_HOST'].'/'.$projectName.'/'.$filePath;
}
It can be used to convert paths which will be inserted into the HTML document.
Edit:
Note, that defining an array with all paths is just a suggestion. It helped me in my projects, as I often restructure my project layout. If you don't do that in your project, you can just define a
$rootDir = $_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1]);
and then include files with
require_once($rootDir . "/home/index.php");
This way, you won't need the config.php anymore.

Try:
<?php
$basePath = dirname(__FILE__);
// Or __DIR__, since PHP 5.3.0
require_once($basePath . "relative/path/from/basePath");
// replace the string with your real relative path
Edits:
Q1) Yes. dirname(__FILE__) describes the absolute path of the directory your files are located in.
Q2) Not necessary. If you know the file which you want to include is just one level or two level up you can also use
For one level - include("../filename.php");
For two level - include("../../filename.php");
and so on..
Note: But I still recommend to use absolute paths.
For your reference:
PHP: Absolute vs. relative paths

Related

Make included file have its relative directory location, not the directory location its being called from

I have a header.php file, which contains files I want to use on different pages:
<link rel="stylesheet" href="css/nav.css" type="text/css">
<link rel="stylesheet" href="css/main.css" type="text/css">
I have the file inside a folder called resources which includes all my css files. I want to have the header so that it can directly link to the css files, but when I try to include the header in my webpages, it includes the path where the file that is including it is stored, not the relative path to where the header file is. How can I make it use the relative path for the header file, not the file where it is being included?
I've tried using, from other answers:
include( dirname(__FILE__) . 'css/main.css');
However, this gives me Not allowed to load local resource and gives the full file destination, but is correct
You should define the path to resources before including header.php:
define("res_path", "../resources/");
include(res_path."header.php");
Then in header care about that path:
<link rel="stylesheet" href="<?php echo res_path;?>css/nav.css" type="text/css">
<link rel="stylesheet" href="<?php echo res_path;?>css/main.css" type="text/css">
And in files that already have the correct path:
define("res_path", "resources/");
include(res_path."header.php");

Loaded styles and css but not displaying properly

So I tried to import a web HTML CSS template into my self-made MVC.
When I open the template itself it works properly. But when I access it through my controller it can not connect to CSS files and does not display proper style. Only blank HTML without any styles.
This is how I am trying to access it
class NewsController {
public function actionIndex() {
$newsList = array();
$newsList = News::getNewsList();
require_once 'views/index.php';
return true;
}
This is code from HTML head where it links the CSS
<link rel="stylesheet" href="css/animate.css" >
<link rel="stylesheet" href="css/icomoon.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/magnific-popup.css">
<link rel="stylesheet" href="css/style.css">
this is how folders are located(highlited the controller, and views folders is a full template ) folders tree:
EDIT
I checked with inspec all the elements are loaded but do not display any styles. Whats the matter?
You need to add './' at start of CSS paths. This allow browser to use absolute file path.
./ is has nothing to do with an absolute file path. It just marks the current direcory.
If you want to use the absolute filepath, do it with php or the equivalent in your template language:
<link rel="stylesheet" href="<?php echo __ DIR __ . DIRECTORY_SEPARATOR . 'blogv4' . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'animate.css'; ?>" />
?>
EDIT: Due to the image of your folder tree you can write:
<link rel="stylesheet" href="blogv4/views/css/animate.css" />
You need to enter the path from your bootstrap file (e. g. index.php), which contains your header.
Make sure the PHP script (in your case, the index.php handling the request) that's calling your Controllers lives in your document root where your assets are.
And, if I am the one, I'd write an helper function for handling my assets, like
<?php
function asset($resource) {
$link = preg_replace('/\//', DIRECTORY_SEPARATOR, $resource);
return $link;
}
?>
Like that, you can render the absolute path of where your assets are by adding the protocol and domain prefix in front on the return value.

CSS not working from relative path with php 'includes'

folder structure
/
|--index.php
+--includes
|--header.html
+--css
|--style.css
I have 2 subfolders in my main project folder. One is a folder called 'includes' and the other one is called 'css'.
I have my
-index.php file in the main folder
-header.html in my 'main/includes' folder
-style.css in my 'main/css' folder
My index.php includes the header.html like this:include_once('includes/header.html'); (this Works!)
My header.html file links the css like this:<link href='../css/style.css' type='text/css' rel='stylesheet'/>
(this does NOT work!)
I don't understand why the css file is not loaded.
I have tried using the base tag, although I'm not sure I'm using it right.
<base href="http://localhost/main" /> (this is NOT working)
You should try using
<link href='css/style.css' type='text/css' rel='stylesheet'/>
As index.php and the css folder lie at the same level.
With
<link href='../css/style.css' type='text/css' rel='stylesheet'/>,
you are asking your server to look after the style.css in upper level directory of index.php which does not exist.
You can also use / because, it points do the document root of the website.
<link href="/css/style.css" type="text/css" rel="stylesheet" />
I don't think you understand how include works. Essentially the code in the referenced file will be copied into the main file, and then processed. So if you're including it into index.php, then you want to reference the CSS file accordingly.
The following should work:
<link href="/css/style.css" type="text/css" rel="stylesheet" />
You'll find it is the most easy to just use absolute paths when using HTML, that way the above like will still be valid, even if you copy it to a file that is in within a folder besides the root.
$siteurl ="http://localhost/project";
(store this variable in config file so that you can use globally)
<link href='../css/style.css' type='text/css' rel='stylesheet'/>
will be changed to
<link href='<?php echo $siteurl;?>/css/style.css' type='text/css' rel='stylesheet'/>
just change from <link href='../css/style.css' type='text/css' rel='stylesheet'/> to <link href='css/style.css' type='text/css' rel='stylesheet'/>
If you are trying to add CSS in html file using PHP require:
<style><?php require("css/style.css");?></style>
Note: <style> tag is important otherwise it will echo plain text

PHP - make paths relative when including file

In a site root I have the following folders and files:
File includes/scripts.php includes links to all css/js files needed for the rest of the pages to function. When including scripts.php from any file in the site root (ex cart.php) all paths work fine. But when including from within a folder (ex. /admin) the paths are not correct, obviously because there isn't a /js or /css dir inside /admin.
I tried several things like changing the paths inside scripts.php from '../css/styles.css' to ./css/styles.css or just /css/styles.css but that didnt work. Also tried include($_SERVER["DOCUMENT_ROOT"] . "includes/scripts.php"); but also without success.
How do I make paths relative inside scripts.php so that no matter where it is included from, all css/js paths are correct and relevant to the site root?
This is an example of some linked files in scripts.php:
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.alerts.js"></script>
<script type="text/javascript" src="js/cookie.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/layout.css">
etc...
EDIT: I see that most of the answers have taken for granted that the files are hosted in a UNIX environment which is not true, it's being developed on a Windows/Apache setup and will be hosted on a UNIX server when finished. So I need a solution that works on both systems so I don't need to change the code whenever I'm editing/uploading the files to the live server.
Includes in PHP
Method 1 - using a constant
Create a constant (eg. ROOTDIR) in one of your root files (eg. index.php, or create a file that you always include relatively before any other include) before you include any other files:
//Place this in a file you always include relatively
define("ROOTDIR", dirname(__FILE__) . "/");
and wherever you include stuff:
//Place this in whatever file
require_once(ROOTDIR . "admin/panels/users.php");
Method 2 - using set_include_path
Alternatively, in the same file, instead of the constants, you could use set_include_path as such:
//Place this in a file you always include relatively
set_include_path(dirname(__FILE__) . "/");
and when you include stuff:
//Place this in whatever file
require_once("admin/panels/users.php");
Method 3 - through the PHP config
If you'd rather be without constants and set_include_path and have access to the PHP config file, you could also change include_path in the config to eg. /var/www/, and then simply use above require_once when including files. More info about that here.
But what about inclusion of scripts and stylesheets, h2ooooooo?
Well, I knew you'd get into that. What I usually tend to do is either make the path relative to root by starting it with an /:
<script type="text/javascript" src="/js/jquery-1.8.0.min.js"></script>
<!-- ^ -->
or you can alternatively set a <base> path in HTML:
<head>
<base href="http://www.mydomain.com/" />
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
</head>
Note: When setting a <base> path, it also specified that all links will be relative to the base path as well so if you have a link in the admin folder pointing towards subdir/ it will link to http://www.mydomain.com/subdir/ and not http://www.mydomain.com/admin/subdir/.
Please do the following changes instead of include($_SERVER["DOCUMENT_ROOT"] . "includes/scripts.php");
<script type="text/javascript" src="<?php echo $_SERVER["DOCUMENT_ROOT"];?><js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="<?php echo $_SERVER["DOCUMENT_ROOT"];?>js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript" src="<?php echo $_SERVER["DOCUMENT_ROOT"];?>js/jquery.alerts.js"></script>
<script type="text/javascript" src="<?php echo $_SERVER["DOCUMENT_ROOT"];?>js/cookie.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER["DOCUMENT_ROOT"];?>css/styles.css">
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER["DOCUMENT_ROOT"];?>css/layout.css">
Solution 1:
Use the base tag in your html <head>, note: that will affect ALL the relative links
<base href="http://yoursite.com/" />
Solution 2:
Define an environment variable in your htaccess file
SetEnv MYSITE_URL http://yoursite.com/
and then in your html echo that environment variable
<script type="text/javascript" src="<?php echo getenv('MYSITE_URL'); ?>js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="<?php echo getenv('MYSITE_URL'); ?>js/jquery-ui-1.9.2.custom.min.js"></script>
...
Solution 3:
Similar to solution 2 but instead create a php constant with your site url and echo it in your html
Solution 4:
Start your asset path with a /
try using these function but you need to place it at the root folder on call it were you need it
function($_file){
php_uname();
$server_info = PHP_OS; // get host os info
$os = strtoupper(substr(PHP_OS, 0, 3));
if($os === 'WIN'){
$path = dirname( $file );
$p = explode(':',$path);
return str_replace(array('\\','\\'), array('/','/'), $p[1]); //return the absolute path
}else{
return dirname( $file );
}
}
example:
include get_path(__DIR__).path/to/asset/file.js

php include file from another directory

Here is a structure example:
/main
/css
style.css
/include
article1.php
article2.php
header.php
index.php
In my header.php I have the following code for the css:
<link rel="stylesheet" type="text/css" href="css/style.css" />
And, for example, in my index.php I have the following as the first line:
<?php include 'header.php'; ?>
Now, everything works fine as it is. Next I'm going to insert the following code in the article1.php file:
<?php include '../header.php'; ?>
The contents (menus and other html) are displayed correctly, however the CSS won't be displayed/recognized at all. Basically what's happening is that the header file is being included but the server isn't respecting the directory parenting. For the CSS to be displayed correctly I'd have to change the link rel for the CSS to ../css/style.css, but if I do so it won't work on files located in the main directory.
I hope I made my problem clear. What am I doing wrong? How can I include files from different directories and preserve the links inside them?
In your site's <head> section, insert a <base> element with the href attribute. Set the href attribute to the base URL of your website, and all relative requests will be sent through that base URL.
<base href="http://my-website-url.com/" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
With a correctly-set base tag, the user's browser will attempt to load your stylesheet from the URL http://my-website-url.com/css/style.css.
Note: this not only affects stylesheets, but all relative links in the document.
It has to do with how pathing works in includes. I recommend pathing things from the doc root whenever possible.
<?php include( $_SERVER['DOCUMENT_ROOT'] . '/header.php' ); ?>
That will work in any of your files.
Instead of using relative paths:
href="css/style.css"
use absolute paths from the webroot:
href="/css/style.css"
You should include your css file from the root. So /css/style.css so way it will always start at the root and then go down from there. I believe that should fix your problem in all cases.
First off, the problem is that your link to your CSS files is wrong. The best thing to do is look at the output of the HTML (view source) from the page. So lets break it down (form index.php):
Index.php is located at domain.tld/index.php. Your css files are located at domain.tld/css/*. When viewing the index file, your header is
<link rel="stylesheet" type="text/css" href="css/style.css" />
which works because you are at the top of the directory (or root) and the links are made relative to this directory. Now when you go up to domain.tld/include/article1.php, you are no longer at the root. It is trying to access:
domain.tld/include/css/style.css
This means you have to build the full link or change your relative. The easy way since the CSS is at the root is just to use the following
<link rel="stylesheet" type="text/css" href="/css/style.css" />
^
This means it will look at the root of the domain for the css directory as such domain.tld/css/styles.css. If your top directory is /main, use /main/css/styles.css
Using relative includes from filed already called as includes is always a problem, each time you specify a relative location, replace your
../some_directory/some_file.php
with
dirname(dirname(__FILE__)) . '/some_directory/some_file.php'
dirname(__FILE__) is the current directory.
May I explain your problem and how to solve it.
An include in php works as in C.
When you include a page that copy/paste content of the page into the first one.
So, there are two files:
include.php
<?php
$var = 'PHP';
?>
main.php
<?php
include 'include.php';
echo $var; // affiche 'PHP'
?>
When you request for "main.php" page you will get the following:
<?php
$var = 'PHP';
echo $var; // affiche 'PHP'
?>
So if you need to include an element to your page. You have two choices:
1. absolute path (better way)
Instead of using relative path, use absolute path. This way allows you to include a file from everywhere without of use of the current path.
2. variable
You can use a variable containing the relative path to the root directory of your repository/website. So each time you have to include a page or create one you have to define a variable as following:
include.php
<?php
$var = 'PHP';
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$currentPath."css/style.css\" />";
?>
main.php
<?php
# path to the root of the website
$currentPath = "../";
include 'include.php';
echo $var; // affiche 'PHP'
?>
To learn more about include, see this page
You have two options
Pass the relative path to the included file
ie.
<link rel="stylesheet" type="text/css" href="<?=$path ?>css/style.css" />
and
$path = "../";
include "header.php";
or 2. you use absolute paths to your files
<link rel="stylesheet" type="text/css" href="/css/style.css" />

Categories