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

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.

Related

can I use magic constant __DIR__ in links?

So, I have a question regarding paths in links. Here's the problem: In my assignment all my links are broken (not all but half of them don't work).
html_start.php includes nav.php and start_html is included in /admin/index.php and so on.
public_html
html_start
nav
styles.css
admin
index.php
user
index.php
index.php
First I've tried using absolute path eg. a href = "/user/index.php" but the assistent warned me that it leads to homepage of my university not my index.php.
If I use relative links, half of them work do to the includes.
Sadly all of these work in my environment but not when it's uploaded to my school so I don't know how it will behave until I upload the assignment and I have only one attempt to correct it.
Now, i use include in almost every page - eg. include( __DIR__.'/app.cfg.php') and that apparently works.
So my question is can I do the same with links? I've read somewhere that it doesn't do the same thing.
Looks like you're working in "root" (localhost?), where absolute links are fine, but when the site gets set up at your school's server, then absolute links point to the school's domain instead of the subdirectory where your project is.
What you need is using <base> tag in combination with relative links. Note that it may mess up your css/js/images, so you'd need to update all paths to be relative (not starting with /). Here's an example:
<html>
<head>
<base href="http://example.com/"/>
[...]
link
The link above would point to http://example.com/dir/page.html. Basically, setting an URL in base tag sets what is the "root" of your website, and all relative links will respect it. You can store the value of base in your site's config and echo it in the template, so when your site is set up on another server you'd update the config file and all links/images/css/etc would work.

Best way to deal with relative paths/base tag

OK, so I've run into an issue with nested php includes, and I want to know what is a good compromise of best practices and ease-of-use.
Here's my website structure:
root
- index.php
-/include
- header.php
- footer.php
-/articles
-article-1.php
-/css
-style.css
So here's the issue: Inside index.php I have an include "include/header.php". Inside header.php I have many relative paths such as <link href="css/style.css>. And inside article-1.php I also have include "include/header.php".
So the index file works. But the article-1 file can't see the css file because the relative link is now looking for /articles/css/style.css. I found out about the <base> tag, and have set that in header.php, and it's fixed all my problems except for anchor links (which I can work around with javascript if I HAVE to), but I'm still concerned about what best practice is. How should I go about doing this correctly without having to prepend every single relative link with a huge php line and also without having to use a javascript hack to make anchor links work?
Thanks!
I ended up using a <base> tag in the header, and then wherever I needed anchor links I used php like so: <a href="http://<?php echo $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];?>#">
This makes the link go to the current page with a # added to the end, so it's the same as using <a href="#">
Let me know if you think I could have done this a better way! Thanks!
I think you can go up a directory with "../", current directory is "./"
So from root/articles/article-1.php, you would get to your stylesheet with ../css/style.css
<link href="../css/style.css">
In my opinion the best practice for this sitution is to go back to the root directory, provided that your project is in the root of your server/webspace.
Use a "/" in the beginning of the links, which is an absolute path.
Example: /css/style.css IS ACTUALLY root->css folder->style.css file

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.

Include html while keeping paths relative to file being included

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.

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