문제

On my site I have my resources folder outside of the root, for example:

/var/www/html/ is the root directory

/var/www/resources/

I currently have a config file that sets the location of the library so I can include it with php like so:

defined("LIBRARY_PATH")  

or 

define("LIBRARY_PATH", realpath(dirname(__FILE__) . '/library'));

which works perfectly when I use:

<?php include_once(LIBRARY_PATH . "/file.php"); ?>

but it doesn't work when trying to add Javascript files:

e.g.

<script src="../resources/library/js/test.js"></script>

links to 'www.website.com/resources/library/js/common.js' or

<script src="<?php echo LIBRARY_PATH; ?>/js/test.js"></script>

links to 'www.website.com/var/www/resources/library/js/test.js'

neither of which work.

Any suggestions on how I can do this without having the js files in or above the root?

도움이 되었습니까?

해결책

Your JavaScript files have to be accessible to the browser because they are executed by the browser and not by the server.

This requires that they have a URL.

Putting the files under the webroot is the standard way to give a static file a URL.

Alternatively, you could write a program (e.g. in PHP) that will read the file and then output it's content to the browser. This is more complicated and makes dealing with cache control headers more fiddly and is not recommended.

다른 팁

Assuming you understand what you're doing and security implications of that!..

You create the linkjs.php script that takes the relative path to the script (from some root dir, perhaps /var/www/resource/js) as a parameter, like:

<script src="/linkjs.php?p=test.js">

In your PHP script you resolve the full file path, check that it's indeed a file under the root dir (to protect against ../ in the parameter), that it's readable by you PHP user, read the content and output it into the response. Don't forget to set content type to text/javascript of course.

Ideally, you should also provide proper caching headers based on the source file modification time, but that is a topic in itself. See the guidelines in other SO questions about proper caching headers for dynamic content.

The upside is that you can do on-the-fly script minification/combining/wrapping/substitutions if you like/need.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top