简体   繁体   中英

File path issue while including a file from other files at various directories

File Structure:

app/
 - index.php
 - core -> header.php, setup.php
 - img -> ...
 - lib -> css->stylesheet.css, js->script.js

I have a header.php file that contains link to CSS and JS files. It looks like this:

<link rel="stylesheet" href="lib/css/stylesheet.css"/>
<script src="lib/js/script.js" type="text/javascript"></script>

I need to include header.php in two other files: index.php and setup.php.

The file loads fine in index.php since app/lib/css/stylesheet.css and app/lib/js/script.js exist. In case of loading from setup.php , it will look for file inside the directory 'app/core/lib/css ... and js ... ' .

I tried solving this problem using absolute path using something like:

$path = realpath($_SERVER['DOCUMENT_ROOT']);

and appending it to link and script tags in header.php The problem is that windows says cant access local resources.

How do I solve this sort of issue? Thank in advance.

Make a config.php file with configurations like

<?php
$webPath = 'http://example.com/';
$jsPath = $webpath . 'lib/js/';
$cssPath = $webPath . 'lib/css/';

Then include config.php in all of your entry points. Entry point here is index.php and setup.php

Once you have that, header.php should have simple code:

<link rel="stylesheet" href="<?= $cssPath ?>stylesheet.css"/>
<script src="<?= $jsPath ?>script.js" type="text/javascript"></script>

You should include your files whether .js or .css files using http:// protocol. You can define constant in your config file as shown below:

define('SITE','http://'.$_SERVER['HTTP_HOST'].'/<project_name>/');

Now you can use SITE constant in your header.php as below:

<link rel="stylesheet" href="<?php echo SITE;?>lib/css/stylesheet.css"/>
<script src="<?php echo SITE;?>lib/js/script.js" type="text/javascript"></script>

Hope it help you. :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM