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.
Related
I am trying make bootstrap.php file that gets called everytime before i open a file, like my css. And i do this since i use the header in every page i need to have all of the links working without having to do multiple header depending on where in my folder structure i am. And this is the error:
Not allowed to load local resource: file:///C:/xampp/htdocs/PHP/assets/css/bootstrap.css
And here is my file structure.
index.php
include ('bootstrap.php');
include (FOLDER_MAIN_HTML.'header.php');
bootstrap.php
define ('FOLDER_ROOT', 'C:/xampp/htdocs/PHP/');
define ('FOLDER_CSS', FOLDER_ROOT.'assets/css/');
header.php
<link rel="stylesheet" href="<?php echo FOLDER_CSS;?>bootstrap.css">
Dont know if its neccesarry but this is my httpd.conf in xampp
DocumentRoot "C:/xampp/htdocs/PHP"
<Directory "C:/xampp/htdocs/PHP">
So thats what i have but it doesent work. Even when when i switch the root folder to __DIR__ it still says no allowed. So do i need a htaccess file, and if so how do i do that? Or is there some other way.
And yes i have searched everywhere for a fix, and the code i have right now is from another post, from here.
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';
I'm trying to create file configuration.php with all path's defiitions.
First, there is the autoload.php file included in index.php just after page and session is started.
require_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'configuration.php';
Const. DIRECTORY_SEPARATOR is default "/" but I tried set DS manualy as "/" too.
Then, in configuration.php:
define('DS', DIRECTORY_SEPARATOR);
define('DIR_BASE', $_SERVER['DOCUMENT_ROOT']);
define('DIR_CONFIG', $_SERVER['SCRIPT_FILENAME']);
define('DIR_APP', DIR_BASE.DS.'app');
define('DIR_ASSETS', DIR_BASE.DS.'assets');
define('DIR_CSS', DIR_ASSETS.DS.'css');
But path generated this way looks following:
<link rel="stylesheet" href="C:/xampp/htdocs/pro_name\assets\css/vendor/bootstrap.min.css">
<link rel="stylesheet" href="C:/xampp/htdocs/pro_name\assets\css/vendor/font-awesome.min.css">
<link rel="stylesheet" href="C:/xampp/htdocs/pro_name\assets\css/app.css">
<link rel="stylesheet" href="C:/xampp/htdocs/pro_name\assets\css/debug.css">
and in Chrome Developer Tool I get for example:
Not allowed to load local resource: file:///C:/xampp/htdocs/pro_name/assets/css/vendor/bootstrap.min.css
I want to create universal paths for localhost and production server. Where I made mistake?
The question doesn't specify this, but I suspect the actual problem is that the production system runs on website.com/index.php and the development system is using localhost/w8/index.php. This extra folder on the dev system causes the issue when the autoloader is set to use / as the project root.
The issue with the chrome dev tools is caused by using $_SERVER['DOCUMENT_ROOT'] which returns the filesystem path instead of the relative website folder path.
To solve this, you need to replicate the production system on your localhost. You can do this by setting a hosts entry to something like project.local and setting up apache to serve the htdocs/w8/ folder when accessing this domain.
Use this guide to modify your hosts file to have the following entry:
127.0.0.1 project.local
Then, add an entry to your apache config to allow requests to the project.local domain:
<VirtualHost project.local:80>
DocumentRoot "C:/xampp/htdocs/w8/"
ServerName project.local
</VirtualHost>
NOTE: This apache config is untested! Your best bet is to copy the existing virtualhost, change * to project.local, and to modify the document root to be the w8 folder instead of the entire htdocs folder.
Now, you should be able to access your project by opening http://project.local in your browser. You can then set / as your DIR_BASE and it should work on both your production server and your test system (as long as you use the alias domain http://project.local when working locally).
I haven't actually tested this, but these are the steps you need to follow to get it working.
There has to be something I'm overlooking but I can't seem to get my includes to work as expected using relative paths. In MAMP the DocumentRoot is configured in httpd.conf like this:
# MAMP DOCUMENT_ROOT !! Don't remove this line !!
DocumentRoot "/Applications/MAMP/projects/journalproject”
I bring up the site at http://localhost:8888/ and the includes work fine if I use a path like this:
<?php include('nav.php'); ?>
But, if I put my include file into a folder, the include doesn't show up on the page:
<?php include('/includes/nav.php'); ?>
This is the path of the include file: /journalproject/includes/nav.php
I'm calling it from here: /journalproject/journals/index.php
I can also get the include to work if I use a path like this:
<?php include('../includes/nav.php'); ?>
I'm not sure why I need to specify the path for the include when an anchor link has no trouble finding the same file using a relative path:
Find nav include
I'm not sure where to go from here. Any help would be greatly appreciated.
I believe that the below doesn't work because it is being treated as an absolute path, as it starts with a "/" which tells PHP to look from the literal "/" directory in Unix Operating Systems:
<?php include('/includes/nav.php'); ?>
Try:
<?php include('includes/nav.php'); ?>
you can specify files relative to the include path without being conscious of where your specific .php file that calls the include/require is located:
http://php.net/manual/en/function.set-include-path.php
set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'])
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.