PHP - make paths relative when including file - php

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

Related

defining root directory for CSS & images in php

This is my code below, i need to set a root directory for css files to access file from anywhere in application. But this is not working for getting images & css files.
define('ROOT', __DIR__);
define('RCSS', ROOT.'\css');
define('RIMAGES', ROOT.'\images');
And my Html Page Content is..
<link rel="stylesheet" type="text/css" href="<?php echo RCSS.'\master.css'; ?>"
You are doing it in a wrong way. Try to use "http://" . $_SERVER['SERVER_NAME'] instead of __DIR__. Because you should pass web path to your html files.

making relative path for include files

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

http://localhost/ appears before path

In the beginning of the PHP file, I am defining the ROOT as
define('ROOT', dirname(__FILE__));
It works when i use something like
require_once(ROOT . DIRECTORY_SEPARATOR . 'config/bootstrap.php');
However, when using the same ROOT while including the css within the HTML seems to create a problem.
<html>
<head>
<title>PrePress ยท Login</title>
<link type="text/css" href=<?php echo ROOT . DS . 'views/type.css ?> rel="stylesheet">
</head>
<body>
Test
</body>
</html>
On tracing the path of the CSS file, the full path starts with http://localhost:8888/Users/.... Here I simply want my path to start from /Users/ which will be able to find my css file, whereas having the localhost changes the path and the file can no longer be found.
<link type="text/css" href="<?php echo $_SERVER["DOCUMENT_ROOT"]."/views/type.css"; ?>" rel="stylesheet" />
You do not need to use that format in an href. Just use
<link type="text/css" href="views/type.css" rel="stylesheet">
To give a relative address, which makes the code much more transportable
use
<?php $path = glob($_SERVER["DOCUMENT_ROOT"]."/views/type.css"); ?>
<link type="text/css" href="<?php $path; ?>" rel="stylesheet" />
You have to set the base url and that should link to your project folder. If you are not using a framework then I suggest you do.
Once you have set your base url you can call css and javascript from your header and footer respectively, and include the header and footer on your pages i.e $this->load->view('includes/header); and $this->load->view('includes/footer);
This is how you would typically call your scripts, I have only mentioned the href property within the tags as you should know the rest.
<script href="<?php echo base_url('link to your script goes here');?>" />
<link href="<?php echo base_url('link to your sheet goes here);?> />

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" />

How to include css/javascript/php-includes file in subdomain from domain

I want to use css, javascript, php-includes from main domain into sub-domain.
Directory structure for main domain.
/root/global/css/css.css
/root/global/javascript/javascript.js
/root/global/include/include.php
Directory structure for sub-domain
/root/sub-domain/index.php
Now css, javascript, php-includes are not working in sub-domain, i.e I get un-stylized page and no javascript, php files are included.
I am doing this way in sub-domain index.php
<link href="../global/css/css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../global/javascript/jquery.js"></script>
<script type="text/javascript" src="../global/javascript/javascript.js"></script>
this is not working for sub-domain but working for other same level directories, I also tried this way
<link href="http://www.mysite.com/global/css/css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://www.mysite.com/global/javascript/jquery.js"></script>
<script type="text/javascript" src="http://www.mysite.com/global/javascript/javascript.js"></script>
It is also not working for sub-domain but working for other directories in same level.
Please see and suggest any possible way to do this.
Thanks.
For sub-domains, this is working without issues, otherwise, you would have another issue within your files location :
src="//www.yourdomain.com/whateverpath/yourfile.js"
Altough www.mysite.com/global/css/css.css looks like an absolute link, in fact it isn't.
If you are on www.mydomain.com it will look for http://www.mydomain.com/www.mysite.com/global/css/css.css which is what you do not want.
To absolute link resources include the scheme (which would be http://www.mysite.com/global/...) or set absolute paths with the trailing slash: /global/css/css.css.
Two options, you can set the "include path" in the php.ini file, or you can use set_include_path() function at the beginning of your script: http://php.net/manual/en/function.set-include-path.php

Categories