include files from anywhere on the server

徘徊边缘 提交于 2019-12-02 15:48:44

问题


I have website running perfectly on production server. I have moved it to another web server. (VPS).

Let me explain you with example: The directory structure:

includes/
        header.php
business/
        index.php
        some other files...
index2.php

In my previous version, I used

include_once(includes/header.php)

in index.php and index2.php. It runs fine. but in my new server setup it's giving me error regarding path (obvious).

ERROR:

include_once(includes/header.php): failed to open stream: No such file or directory

And because of that:

Fatal error: Class 'EncryptionClass' not found

I think there are some server configurations which I need to do. But, I don't know how? Please guide me. Let me know if you want more information.


回答1:


if using PHP 5.3+ Try using:

include_once(__DIR__.'/includes/header.php');

DIR is a magic constant that will return the full directory that the file is in.




回答2:


You could supply an absolute file system path to the include:

include_once($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");




回答3:


I would simply add your includes directory to the include_path. For example, in index2.php

set_include_path(implode(PATH_SEPARATOR, [
    __DIR__ . '/includes', // relative to this file, index2.php
    get_include_path()
]));

include_once 'header.php';

and similarly in business/index.php...

set_include_path(implode(PATH_SEPARATOR, [
    __DIR__ . '/../includes', // relative to this file, business/index.php
    get_include_path()
]));

include_once 'header.php';

Personally, I would use PSR-0 file-to-class name mappings and configure an autoloader, eg

includes/EncryptionClass.php

class EncryptionClass { ... }

index2.php

spl_autoload_register(function($class) {
    require_once __DIR__ . '/includes/' . $class . '.php';
});

$encryptionClass = new EncryptionClass();


来源:https://stackoverflow.com/questions/21472051/include-files-from-anywhere-on-the-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!