简体   繁体   English

PHP require_once路径

[英]PHP require_once path

I have a website with the following directory structure: 我有一个具有以下目录结构的网站:

index.php
connections/database.php
contacts/details.php
inc/functions.php

The index.php, database.php and details.php page all require the functions.php page. index.php,database.php和details.php页面都需要functions.php页面。 I'm including this in these pages as follows: 我在这些页面中包括以下内容:

$path = dirname(__DIR__);
// looks like this: /Library/WebServer/Documents/clients/acme
require_once $path.'/inc/functions.php';

This is working well on my Mac development server. 这在我的Mac开发服务器上运行良好。 I just uploaded the files to the production server which is running IIS/Windows 2008, so I knew there would be some path issues. 我只是将文件上传到运行IIS / Windows 2008的生产服务器,所以我知道会有一些路径问题。

I had to change the code to include the functions.php file to this: 我必须更改代码以将functions.php文件包含到此文件中:

$path = dirname(__DIR__);
// looks like this: C:\inetpub\wwwroot\client_sites\acme
require_once $path.'\inc\functions.php';

This is all working so far, but I'm wondering if there's an easy way to make this dynamic so I don't have to modify the string for the correct backslash or forward slash depending on the server environment? 到目前为止,所有这些工作正常,但是我想知道是否有一种简单的方法可以使此动态变化,因此我不必根据服务器环境为正确的反斜杠或正斜杠修改字符串? I'll forget at some point or the client might change servers and then this will break and require manually changing the paths. 我会忘记某个时刻,否则客户端可能会更改服务器,然后这将中断并需要手动更改路径。

Is there a way to automatically handle the path regardless of the server OS environment? 是否有一种方法可以自动处理路径,而不管服务器操作系统环境如何?

Well, there's the DIRECTORY_SEPARATOR constant in PHP, but it's not necessary to use it. 嗯,PHP中有DIRECTORY_SEPARATOR常量,但是没有必要使用它。 If you use forward slashes, you'll be fine in all cases. 如果使用正斜杠,则在所有情况下都可以。 Windows won't mind. Windows不会介意的。

Define the DIRECTORY_SEPARATOR in your app bootstrap or autoload. 在应用程序引导程序或自动加载中定义DIRECTORY_SEPARATOR。

eg 例如

<?php
define('DS', DIRECTORY_SEPARATOR); // set the 3rd param to true to define case-insensitive

Some PHP Frameworks (like CodeIgniter) do it the same way to ensure proper dirpaths. 一些PHP框架(例如CodeIgniter)以相同的方式来确保正确的目录路径。

So to re-create the path in your example: 因此,在示例中重新创建路径:

<?php
define('DS', DIRECTORY_SEPARATOR);

require_once dirname(__DIR__).DS.'inc'.DS.'functions.php';

Check out the PHP Manual for Predefined Constants and define() . 查看PHP手册中的预定义 常量,然后define()

Also consider using set_include_path() and spl_autoload_register() . 还可以考虑使用set_include_path()spl_autoload_register()

Happy coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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