note 85855 added to function.include
| From: | thedanevans at gmail dot com | Date: | Sun, 21 Sep 2008 06:02:31 +0000 |
| Subject: | note 85855 added to function.include | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144584@lists.php.net to get a copy of this message | ||
Linking to CSS/JavaScript resources through an included file has bugged me for a long time because
if I have a directory structure like:
/www
index.php
/sub_dir
index.php
/includes
header.php
/style
main.css
where both index.php files include header.php and the header.php file includes something like:
<link rel="stylesheet" type="text/css" href="style/main.css">
This will be included for /index.php but not for /sub_dir/index.php. I read through a few different
ways to use relative includes but those are generally meant for the php include function not the
HTML <link>. I didn't really love the idea of a new function that I would pass both the
filename and a '../' string into which it could use in the href. I also didn't want
to just use /style/main.css because in development it is not hosted in my root directory. Although I
could change my configuration or my include_path I really just wanted to find a way for PHP to
figure out the relative path for me. I finally found a solution that met my needs and here it is:
<?php
$include_dist = substr_count(dirname(__FILE__), DIRECTORY_SEPARATOR);
$calling_dist = substr_count(dirname($_SERVER['SCRIPT_FILENAME']),
DIRECTORY_SEPARATOR);
?>
<link rel="stylesheet" type="text/css"
href="<?=str_repeat('../', $calling_dist - $include_dist +
1)?>style/main.css">
In this case I added one to the difference to account for the fact that the include is one directory
away from the base. This also means that str_repeat won't be passed a negative value, which
would cause an error. dirname(__FILE__) gets the directory of the file being included while
dirname($_SERVER['SCRIPT_FILENAME']) gets the directory of the file including it. The
script simply finds the difference in how far off the base directory the two are and prints the
appropriate number of '../' before the URL.
NOTE: dirname(__FILE__) can be replaced by __DIR__ in PHP greater than or equal to 5.3.0
----
Server IP: 128.39.198.38
Probable Submitter: 76.90.126.27
----
Manual Page -- http://www.php.net/manual/en/function.include.php
Edit -- https://master.php.net/note/edit/85855
Del: integrated -- https://master.php.net/note/delete/85855/integrated
Del: useless -- https://master.php.net/note/delete/85855/useless
Del: bad code -- https://master.php.net/note/delete/85855/bad+code
Del: spam -- https://master.php.net/note/delete/85855/spam
Del: non-english -- https://master.php.net/note/delete/85855/non-english
Del: in docs -- https://master.php.net/note/delete/85855/in+docs
Del: other reasons-- https://master.php.net/note/delete/85855
Reject -- https://master.php.net/note/reject/85855
Search -- https://master.php.net/manage/user-notes.php