且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 中的基本 URL

更新时间:2023-02-26 18:12:45

我已经修改了大部分 $_SERVER[] 标签和属性,以及 parse_url().

I’ve tinkered around with most of the $_SERVER[] tags and attributes, as well as parse_url().

不要修补它们.没有干净/自动化的方式来做你正在做的事情.只需在配置文件中手动设置基本路径 &再也不用担心它——相对路径.而如果需要设置base URL,过程类似.

Don’t tinker with them. There’s no clean/automated way to do what you are doing. Just set a base path manually in a config file & don’t worry about it—relative paths—ever again. And if you need to set a base URL, the process is similar.

就文件基本路径而言,您应该像这样显式设置 $BASE_PATH:

So as far as a file base path goes, you should explicitly set a $BASE_PATH like this:

$BASE_PATH = '/full/path/to/your/codebase/here/';

如果您不知道您的文件系统基本路径是什么,只需将这行代码放在您的 PHP 代码中即可;比如 index.php:

If you don’t know what your file system base path is, just place this line of code in your PHP code; like index.php:

echo "Your path is: " . realpath(dirname(__FILE__)) . "<br />";

然后加载该页面.靠近顶部的某处将是这样的文字:

Then load that page. Somewhere near the top will be this text:

你的路径是:/full/path/to/your/codebase/here/

Your path is: /full/path/to/your/codebase/here/

然后使用该设置,您可以将代码更改为如下所示:

Then with that set you can change your code to be something like this:

然后像这样设置你的 include_once:

And then set your include_once like this:

include_once $BASE_PATH  . 'includes/myfile.php';

有些人可能会说您应该直接使用 $_SERVER['DOCUMENT_ROOT'] 甚至 dirname(__FILE__) ,这意味着您可以通过这种方式简化代码可移植性.但是为安装设置文件路径的方式可能会有所不同,因此它永远无法正常工作&你被奇怪的服务器怪癖缠住的机会很高.

Some might say you should use $_SERVER['DOCUMENT_ROOT'] or even dirname(__FILE__) directly with the implication being that you can simplify code portability that way. But the way file paths are set for installs can vary so it just never works well & the chances of you getting snagged on an odd server quirk is high.

当您移动代码时,***只在配置文件中手动设置 $BASE_PATH,而不是处理像 $_SERVER 这样的 PHP 常量不存在而引起的头痛问题安装、设置和配置.

It’s always best to just to manually set a $BASE_PATH in a config file when you move code than deal with the headaches caused by PHP constants like $_SERVER not being consistent between installs, setups & configurations.

就基本 URL 而言,只要在本地开发设置中遵循相同的想法即可:

And as far as a base URL goes, just follow the same thinking with this being on your local development setup:

$BASE_URL = '/websitename/';

这是在您的生产服务器上:

And this being on your production server:

$BASE_URL = '/';

所以设置了 $BASE_URL 然后你可以这样做:

So with that $BASE_URL set then you can just do this:

我有几乎所有链接的基本脚本,除了包括页眉和页脚文件.

I’ve got the base script for almost all of the links, except for the including header and footer files.

现在只需在您可能需要通过带有 $BASE_URL 的 URL 请求的任何路径之前添加 &你应该很高兴.

Now just prepend any path you might need requested via a URL with $BASE_URL & you should be good to go.