Reputation: 8296
I'm working on my first website using php. I came up with a good way, or so I thought, to deal with including the css sheet depending on where I am. For example, I have a form that I submit to with this code:
$root = '../';
function died($error)
{
include '../includes/header.php';
echo "We are very sorry, but there were error(s) found with the form your submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
include '../includes/footer.php';
die();
}
I set the variable $root to have "../" and then here is the relevant part of header.php:
<link href="<?php echo $root;?>styles/styles.css" rel="stylesheet" type="text/css" />
I would think that it would put in "../" in front of styles, but it doesn't put anything. Why doesn't this work?
Thanks!
Upvotes: 1
Views: 255
Reputation: 38526
$root
is not in scope for the function (im assuming..)
add global $root;
to the top of the function and it should work.
$root = '../';
function whatever() {
global $root;
echo "<link rel=stylesheet type=text/css href=\"" . $root . "something.css . "\">";
}
Upvotes: 1
Reputation: 6186
For referencing files such as this you simply need to start the path with a forward slash and the path is then relative to your root directory...
<link href="/styles/styles.css" rel="stylesheet" type="text/css" />
Upvotes: 0
Reputation: 12078
In this situation my suggestion is to use $root = "FULL path";
So for example... if your web root is in "/var/www/html/" and you are working on a project lets call it sampleProject which is in "/var/www/html/sampleProject".
Set $root="/sampleProject/; and this way when you use things such as styles/styles.css"/> you end up with which is what you want.
Unlike other answers this makes your code more portable in my oppinion. For example if you move your site "sampleProject" to /var/www/html/dir1/dir2/dir3/sampleProject/ all you need to do is change $root="/dir1/dir2/dir3/sampleProject/" and it will still work. Whereas if you use explicit full path as some suggest you will have to change this everytime you move your site.
Upvotes: 0
Reputation: 13709
You can make the path to your CSS file absolute:
<link href="/styles/styles.css" rel="stylesheet" type="text/css" />
Prefixing a URL with a forward slash (/
) will make the URL relative to your site's root. The above example would reference something like http://example.com/styles/styles.css
. This way, you can put all your CSS in a folder at the root of your site and not have to worry about the path at all.
Upvotes: 0