开发者

PHP file outside doc root needs files outside and inside the document root

开发者 https://www.devze.com 2023-01-03 01:42 出处:网络
I have a library of classes, all interrelated. Some files are inside the document root and some are outside using the <Directory> and Alias features in httpd.conf

I have a library of classes, all interrelated.

Some files are inside the document root and some are outside using the <Directory> and Alias features in httpd.conf

Assuming I have 3 files:

webroot.php (Inside the document root)
alias_directory.php (Inside a folder outside the doc root)
alias_directory2.php (Inside a **different** folder outside the doc root)

If alias_directory2.php needs both webroot.php and alias_directory.php, This does not work. (Remember alias_directory.php and alias_directory2.php are not in the same locations)

require_once $_SERVER['DOCUMENT_ROOT'].'/webroot.php'; //(ok)
require_once $_SERVER['DOCUMENT_ROOT'].'/alias_directory.php'; //(not ok)

This does not work because alias_directory.php is not in the doc root.

Similarly

require_once $_SERVER['DOCUMENT_ROOT'].'/webroot.php'; //(ok)
require_once dirname(__FILE__).'/alias_directory.php'; //(not ok)

The problem here is that dirname(__FILE__) will return the path for alias_directory2.php not alias_directory.php.

This works:

require_once $_SERVER['DOCUMENT_ROOT'].'/webroot.php'; //(ok)
require_once '/full/path/to/directory/alias_directory.php'; //(ok)

But is very nasty and is a maint开发者_开发百科enance nightmare if I decide to move my library to another location.

How do I solve this problem, is seems that I need a way to resolve an Alias folder properly.


PHP will not be able to resolve the location of your alias_directory.php file. You will need to supply the location of the alias_directory.php file yourself. Either as an absolute path, or relative to alias_directory2.php or the DOCUMENT_ROOT

Example:

If your file locations look something like this:
/var/www/webroot.php
/var/otherdir1/alias_directory.php
/var/otherdir2/alias_directory2.php

From alias_directory2.php you can now include alias_directory.php by either:
require_once('/var/otherdir1/alias_directory.php');
or
require_once(dirname(__FILE__).'/../otherdir1/alias_directory.php');
or
require_once($_SERVER['DOCUMENT_ROOT'].'/../otherdir1/alias_directory.php');

To use relative paths, alias_directory.php should be located somewhere close to alias_directory2.php or DOCUMENT_ROOT

Another solution would be to add the folders in question to the include_path, and use require_once('alias_directory.php'); without path specification.


Use dirname twice. Once to get the directory of the current file, again to get the parent of that directory, then step back down into the other directory;

require_once dirname( dirname(__FILE__) ) . '/other_dir/alias_directory.php';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号