Include html while keeping paths relative to file being included - php

Have several html snippets that I want included in a 'parent' file.
The parent file contains relative paths.
These snippets also contain relative paths, relative to their location - not relative to the file they will be included into.
For example, one snippet is the header, common to all pages on the site.
<div style='background:url(img/bg.jpg)'>
<img src='img/logo.png'>
</div>
This will be inserted into the existing page as follows:
<div style='background:url(img/gradient.jpg)'>
<?php include '../includes/header.txt'; ?>
</div>
Example is very greatly simplified, the actual files have many paths.
I am NOT in control of the files that will be included.
Which means I cannot add PHP variables to the urls.
I also cannot make the paths absolute in any way.
For the included files - because I have no control over the html.
For all files - because the final pages are dev'd on several machines, and must work whether at http://www.mysite/myfile, http://localhost/mysite/myfile, or even http://127.0.0.1/~/anyuser/...
Some ideas I've had:
php include: include '../includes/header.txt';
Paths come out relative to the file it has been included into.
Including each snippet as an iFrame:
Page layout isn't very iFrame friendly. Besides SEO & page load issues.
Parsing the page and replacing all paths using a parser.
The pages are not 100% valid HTML (no control over them) and the parser coughs and rolls over dead. Besides the ridiculous server load.
Using base tags
Works beautifully in every real browser.
But Internet Explorer 7, 8, and 9 just ignore the base tag (outside the head).
One base tag could be declared in the head, but then all the other paths on the page (and probably in the CSS files) will be all wrong.
BaseTag Usage:
<?php
echo "<base href='$path_to_includes_folder' />";
include '../includes/header.txt';
echo "<base href='$path_based_on___file__' />";
?>
As I understand, this exactly why the base tag was created, and is supported in every decent browser - so that we can, in the middle of one HTML file, tell the browser that I am about to include a second HTML file, and all paths should be relative to the new location. This worked beautifully in IE6, and I assume there must have been some logic in dropping support for it. Some logic which escaped Opera, Webkit, and Mozilla.
The only posts I can find on the subject laud Microsoft for dropping support, without giving even a hint of a reason why dropping support for something which is an accepted standard (in use in all browsers of the time) and useful is a good thing.
Now, I hate developing for IE with a passion, but cannot ignore it. They still have almost 1/3 of the users!
So, how to include php snippets with relative paths, and keep them relative to the file being included?
And can anyone please tell me if there is any reason at all MS dropped base support, or what can be done to help get it back?

For these situations I use the following,
$PROTOCOL = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$DOC_ROOT = $PROTOCOL.'://'.$_SERVER['SERVER_NAME'];
//The project path points to the root file (index.php, or whatever your index file is).
$projectRoot = dirname($DOC_ROOT.$_SERVER['SCRIPT_NAME']).'/';
Then you could do (using your example)
<div style='background:url(<?php echo $projectRoot; ?>img/bg.jpg)'>
<img src='img/logo.png'>
</div>
This will give you a dynamic absolute path.

Related

Accessing <link>, <script>, < img> and <a> from anywhere

I have header, menu and footer include files that maybe accessed from anywhere in a folder structure. To date everything that those file load I have given a full url simply because I can’t find any other reliable way to load them from anywhere in the folder structure. Whilst this works, it is far from ideal and totally useless when it comes to developing with XAMPP.
<?php include(__DIR__ . '/inc_menu.php');?>
This works perfectly when ‘including’ or ‘requiring’, can someone please explain how to make something similar work with <link>, <script>, < img> and <a>?
Use URLs relative to the root directory for the site. i.e. URLs that begin with a / character.

php include results in page being written in pre

I'm learning php, been trying to make a cms, but when I use an include for the header this results in the page appearing as if it were written in pre tags. There's no errors when I debug or anything. And I'm completely stumped. When I put the header back in without the include it renders just fine.
<?php include("..\includes\layouts\header.php"); ?>
That's the include I'm using.
I've tried using the full path name, tried it in different browsers and using :
include($_SERVER["DOCUMENT_ROOT"]
Check that you are closing your php tags, ending your strings with semi colons etc.. My guess is that your html is being sucked into the php code which freaks out and just dumps it.
Maybe try one of the validators such as http://phpcodechecker.com (I have not used this one so I cannot comment on it's effectiveness)
Edit: I am rereading your post and I think I understand what you are trying to say - your header contains the path to your css and when you put it in a separate php file the css doesn't work? So the first thing to do is determine if the issue with the php path or the css path inside the header.php file. Look at your source code to see if the header code is being included - if it is then play around with the css path - though including the header in a php file will not cause that css path to change.
I am guessing that your header is not included at all from your mention of paths. include() works from the loading file's location. The path it wants is a server path and not a url. The one that you have above: ../includes... means that you have an include folder at the same level as the loading file such as (assume index.php is the main file):
/includes/layouts/header.php
/somedirectory/index.php
The ../ means - drop down one directory then go up from there.
If your path is more like:
/includes/layouts/header.php
/index.php
Then the include would be:
include('./includes/layouts/header.php');
Let me know if that works - if it doesn't try to explain your directory structure.

CSS failure when using INCLUDE Function

I downloaded a Template + CSS File for a Website that I'm Building, the template worked well until I tried to break it down and put every code in its own file (for easy modification and editing in the future).
So, when I cut the head part which included (Title + Meta Data .. etc ), and put it in its own file, and replaced it (for sure) with an include() function, I lost the CSS styles and returned to the basic & standard style (Black & white with no extra format .. etc)
Where did I Go wrong? Knowing that here is the include function that I've used:
<?php
include 'files/head.php';
?>
With an URL like file:///C:/xampp/htdocs/test6/index.php PHP is NOT executed. You must run it with apache being involved. Currently you are opening your PHP script as a regular txt or html file - it is just passed to browser without processing.
In order to make include function work you must run it with apache. As you are using xamp, I think you should simply open it with URL like http://localhost/test6/index.php In this case, apache will get that request and pass it to PHP. PHP engine will interpret your PHP script and "replace" include files/head.php with a content of head.php.
If everything is Ok, after pressing Ctrl+U (or looking at HTML with Developer Tools or Firebug) you should see a content of head.php instead of <?php include ....
Please note that css files should be linked with relative URL like css/screen.css. Or absolute URL like http://localhost/test6/css/screen.css. like Search for relative and absolute URLs in google for more info.

How to use images and php includes across multiple directories?

I am brand new to PHP. I want to use it to include a universal header and footer in an html/jquery site. Currently I am using includes to do this:
<?php include('../includes/footer.php'); ?>
This works fine. Where I encounter a problem is with any images in the header or footer.
An explanation of my file structure:
Root folder: contains index.php and the folders "includes", "img", "php" etc.
php folder: contains gallery.php
includes folder: contains header.php, footer.php
When viewing the index.php all images in the header and footer show properly, but, because they are linked relatively (ex "img/facebook.png"), the do not show in gallery.php. To work they would need a ../ included. But then this would defeat the purpose of a universal header.
Thus I am trying to figure out how to link the images in the includes files in way that is doesn't matter where the php file is located. I have read this thread (which sounds like my problem) but I do not understand any of the answers. I have also read things that suggest $_SERVER['DOCUMENT_ROOT'] .'/folder/';, in conjunction with an echo to display the image. I tried this in my footer.php with this code:
<?php
$path = $_SERVER['DOCUMENT_ROOT'] . '/img/';
$image = ($path . "facebook.png");
echo "<img src=\"$image\" />"; ?>
When I view the page though, I end up with a little torn paper icon instead of my image. I assume this means that the path is incorrect, but I do not know why. facebook.png resides in the img folder. This problem occurs on both index.php and gallery.php.
After this rather long winded explanation (sorry), my mains questions are:
1) How do I get images to show up properly in my includes across multiple directories?
2) If I am going about this in the right way with the echo, what are the possible reasons why it is not working?
Once again, I know nothing about php, so if you could try to make your answers as basic as possible, it would be much appreciated.
Thank you!
Instead of img/facebook.png, add a / before the img/ like this: /img/facebook.png
This says "go to the root, and look for the img folder there. All your images should work fine then. The path of the images are absolute or relative based on the HTML page you're viewing, not which files you use to create it.
Though there's probably not much of reason for a "php" folder - just keep all your pages in the root directory.

Best practices with multiple directories in HTML

I haven't found a clear answer to this question (but have determined the HTML tag is more trouble than it's worth.)
When you're working with multiple directories on a website, how do you make sure relative links to the rest of your site work as you change your current directory? I don't want my link to "/index.php" to actually link to "/support/index.php" when I go to the support directory.
We're using PHP, so I could use output buffering to change links, but I want to see if others have any good ideas. Could also implement it through Smarty in one way or another. I haven't built a website from scratch that has used multiple directories simply because I don't know of an easy way to deal with this, but the problem shouldn't be too difficult.
(Running on IIS, but obviously it would be better to let it work on any server.)
you could declare a base_url variable, or declare a constant containing your base url
e.g.
DEFINE('BASE_URL', 'http://example.com/');
when using links
e.g.
Home
You already have everything you need
how do you make sure relative links to the rest of your site work as you change your current directory?
we're using absolute links for that
I don't want my link to "/index.php" to actually link to "/support/index.php" when I go to the support directory.
Lucky you, it will never happen
/index.php is absolute path and will never point anywhere beside /index.php.
/ is not just for decoration. It the meaning of slash at the beginning of the path is "root directory". So, /index.php means index.php placed in the root directory.
/support/index.php means index.php placed in the support directory which is placed in the root
easy-peasy. just always use absolute path (not URL which is senseless)
I store a “base” URI in two locations: (i) on the PHP/Zend Framework server, my configuration.xml file holds conventional values such as URIs; (ii) on the client side a more shallow, hidden <form/> holds other (less security compromising) values such as a base URI.
The form, by the way, looks something like this:
<form id="AppSettings" action="#">
<input type="hidden" id="MyBaseUri" value="http://superuser.com"/>
</form>
Add <base href="http://www.domain.com/"> to your <head> tag. This will make all relative links start from the directory given as href. Then use relative links like support/index.php not beginning with/ (i.e. not /support/index.php)
Note: Make the <base> tag the first tag in your <head> section, as all links after that will be interpreted from that base dir. (e.g. <link href="relative/path"> will already use the base dir if it is defined above.
Advantage: you can move your whole page to a subdirectory like http://www.domain.com/page and only have to change the <base> tag. If you use links like /support/index.php they will always start from the root directory (i.e. http://www.domain.com/)
Dynamic base dir for url rewrites:
<?php
if (preg_match("/https/i",$_SERVER["SERVER_PROTOCOL"]))
$protocol = "https";
else
$protocol = "http";
echo '<base href="'.$protocol.'://'.$_SERVER["HTTP_HOST"].dirname($_SERVER["SCRIPT_NAME"]).'/">';
?>

Categories