问题描述
我使用的是 000webhost,它使用根文件夹中的 public_html 文件夹作为站点的可见根.在那个文件夹中,我有一个包含一些 php 脚本的资产文件夹,以及包含 php 索引页面的其他文件夹.使用 require "/assets/includes/scriptname.php"; 不起作用,因为它试图找到 public_html 的同级文件夹.我可以编辑 .htaccess 以更改相对于 php 查找的根文件夹,但我不知道如何操作.
i'm using 000webhost, which uses a public_html folder in the root folder as the visible root for the site. in that folder, i have an assets folder with some php scripts, and other folders with php index pages. using require "/assets/includes/scriptname.php"; does not work, as it tries to find a sibling folder to public_html. i'm allowed to edit .htaccess to change the root folder relative to the php lookup, but i don't know how.
文件树:
public_html (within root, but simulated root) folder1 index.php folder2 index.php folder3 index.php assets subfolder subfolder index.php
简而言之,如何在 /public_html/ 中创建提到的代码点而不显式声明它(最好作为 .htaccess 更改,因为我希望我的代码能够移动到无需重写任何内容的不同主机).
in short, how do i make the mentioned code point inside /public_html/ without explicitly declaring it (preferably as a .htaccess change, as i want my code to be able to be moved to a different host without rewriting anything).
对于 .htaccess 重写的答案,您能解释一下它的每一行是如何工作的吗?谢谢.
for an answer with the .htaccess rewrite, could you explain how each line of it works? thanks.
推荐答案
.htaccess 对您没有帮助.它是一个 apache 配置,它不会以任何方式影响 php 的行为.
.htaccess does not help you. it is an apache configuration and it does not affect the behavior of php in any way.
代码:
require "/assets/includes/scriptname.php"
告诉 php 使用绝对路径包含文件.不推荐使用硬编码的绝对路径,因为当您将其移动到另一个目录或具有不同路径的不同服务器时,代码将不起作用.
tells php to include a file using an absolute path. using hardcoded absolute paths is not recommended because the code won't work when you move it into another directory or on a different server that has different paths.
指定包含文件路径的最佳方法是在运行时生成它,从包含程序的路径开始.php 函数 dirname() 和常量 __dir__ 是这里的帮手.
the best way to specify the path of an included file is to generate it runtime, starting from the path of the includer. the php function dirname() and the constant __dir__ are the helpers here.
给定示例文件结构:
public_html | - index.php | - assets | | | - somescript.php | - includes | - header.php | - footer.php
假设您需要在 index.php 中包含 assets/somescript.php.在 index.php 中写入:
let's say you need to include assets/somescript.php in index.php. write this in index.php:
require __dir__.'/assets/somescript.php';
魔术常量 __dir__ 包含使用它的文件的目录.对于 index.php,__dir__ 设置为 '/(...path-to-your-user-directory...)/public_html'.
the magic constant __dir__ contains the directory of the file where it is used. for index.php, __dir__ is set to '/(...path-to-your-user-directory...)/public_html'.
如果 somescript.php 需要包含 header.php 它应该这样做:
if somescript.php needs to include header.php it should do it like this:
require dirname(__dir__).'/includes/header.php';
等等.
通过这种方式,您可以将整个应用程序移动到不同的目录、不同的服务器甚至不同的操作系统上,它仍然可以工作.
this way you can move the entire application to a different directory, on a different server and even on a different os and it will still work.