Reputation: 43
My question is similar to PHP include file strategy needed. I have the following folder structure:
/root/pages.php
/root/articles/pages.php
/root/includes/include_files.php
/root/img/images.jpg
All pages in the "/root" and "/root/articles" directories have a "header.php" and "footer.php" file included within them, which are stored within the "/root/includes" directory.
The header and footer pages both contain images stored in the "root/img/" directory.
As suggested by:
How to use a PHP includes across multiple directories/sub directories with relative paths
I tried the **dirname**
solution and the $_SERVER['DOCUMENT_ROOT]
solution to include the header and footer in the files stored in the root directory and articles subdirectory.
However, I run into issues when I try and use either method (within the header and footer files) to link images:
<img src=" <?php echo dirname(__FILE__). '/img/image.jpg';?>">
Chrome fails to display the images and throws the following error:
locally: Not allowed to load local resource: file:///C:/root/img/image.jpg
on the server: GET http://host.com/home/public_html/root/img/image.jpg 500 (Internal Server Error)
I have checked the URL's and they appear to be correct. Having googled for solutions, I found that chrome prevents the display of files that contain it's complete file path for security reasons.
How do I get around this? or is there an alternative way to include files (including images) into files stored in any subdirectory?
Upvotes: 4
Views: 3437
Reputation: 33813
for your included scripts try setting the includes_path
using set_include_path
set_include_path( $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR );
Then, to include a script within your pages you can use:
include( 'script.php' );
For the images, prefix the path with a leading slash /
~ ie:
<img src='/img/image1.jpg' />
It tends to be easier to use root relative paths rather than directory relative paths so prefixing with the leading slash means a folder within the root.
Upvotes: 1
Reputation: 1213
Use ../img/image.jpg for including in files inside /root/articles.
Use img/image.jpg for including in files inside /root
Upvotes: 0
Reputation: 344
@sandeep's answer is partially right. because
$_SERVER['DOCUMENT_ROOT'];
will again give back fully qualified path to the root.
<img src=" <?php echo 'http://localhost/favicon.ico';?>"/>
will return image back because now I am not giving it local path as per your problem but url of the server I am running.
Upvotes: 2
Reputation: 576
This may be help you
$url = $_SERVER['DOCUMENT_ROOT'].'/img/image.jpg';
<img src="<?=$url?>">
Upvotes: 0