I have the image directory, mysite/2012/5/15/image.jpg, and I have my header and footer at mysite/. Then I fetch image.jpg from the database and display in a another page along with the title and comments (if any) submitted by users. Inside header.php and footer.php, I point to a css file that is also located in mysite/ directory. my question is: what is the best way to access the header and footer from my image directory? The way i'm doing it is as follows:
include('../../../header.php');
include('../../../footer.php');
but the after I do this and try to display the page, the css file doesn't load because it doesn't not exist in the image directory. To handle this, I put a bunch of if statements in the header and footer:
if(!strcmp($thisPage,"images")) {
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../file.css\" media=\"screen,projection\" />";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../file2.css\" media=\"print\" />;";
}
else
{
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"file.css\" media=\"screen,projection\" />";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"file2.css\" media=\"print\" />";
}
Is there a better way of doing this?
Thanks in advance!
I would suggest you use absolute paths instead of relative paths.
If you are concerned that you may want to change your directory structure and don't want a huge hassle of replacing all the absolute paths, then you could store the absolute path in a PHP variable or constant, or even an Apache server variable, so if your directory structure changes, you only have to update one variable:
define("CSS_PATH", "http://mysite.com/css");
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"". CSS_PATH ."/file.css\" media=\"screen,projection\" />";
// OR
// add `SetEnv CSS_PATH "http://mysite.com/css"` to your Apache config file or envvars file
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_SERVER["CSS_PATH"]}/file.css\" media=\"screen,projection\" />";
You can use a constant or you can simply use:
echo $_SERVER["HTTP_HOST"]; //outputs www.example.com
which gives you the domain of your website.
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://". $_SERVER["HTTP_HOST"] ."/css/file.css\" media=\"screen,projection\" />";
However, one correct to what Travesty3 has when you are linking to a style sheet you can't use the file system location, you need to use a URL for CSS files.
define("CSS_PATH", "http://mysite.com/css");
Normally when I start a site one of the first things I do is setup constants like so:
define('ROOT_DIR',$_SERVER['DOCUMENT_ROOT']);
define('SITE_URL','http://www.example.com/');
define('JS_DIR',SITE_URL . 'js/');
define('CSS_DIR',SITE_URL . 'css/');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.