PHP - 如何确定文件在 public_html 文件夹中?

PHP - How to determine the file is in public_html folder?

我在包含文件中使用了以下 $_SERVER 变量。

$page_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip_address = $_SERVER['REMOTE_ADDR'];

当我将此文件包含到位于我的 Cron 作业主目录中的 PHP 脚本中时,它向 Undefined array key "HTTP_HOST"Undefined array key "REQUEST_URI"Undefined array key "REMOTE_ADDR" error_log 文件.

为了避免这种情况,我想让这段代码仅在文件位于 public_html 目录中时显示。用PHP if语句怎么说呢?

谢谢!

/**
 * Check if file is in public directory. This will not work if running via CLI.
 *
 * @param bool $checkCallerScript Set to `true` to check for caller script using trace.
 * @return bool Return `true` if it is in public directory, return `false` for otherwise.
 */
function isInPublicDir(bool $checkCallerScript = true): bool
{
    if (!isset($_SERVER['HTTP_HOST']) || !isset($_SERVER['REMOTE_ADDR'])) {
        // if no HTTP or ip address from user.
        return false;
    }

    if (!isset($_SERVER['DOCUMENT_ROOT']) || empty($_SERVER['DOCUMENT_ROOT'])) {
        // if no document root. run from CLI don't have this value.
        // see https://www.php.net/manual/en/reserved.variables.server.php for more details.
        return false;
    }
    $docRoot = str_replace(['\', '/', DIRECTORY_SEPARATOR], DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT']);

    if (true === $checkCallerScript) {
        $traces = debug_backtrace();
        if (is_array($traces)) {
            foreach ($traces as $trace) {
                $callerFile = str_replace(['\', '/', DIRECTORY_SEPARATOR], DIRECTORY_SEPARATOR, ($trace['file'] ?? null));
                if (!isset($callerFile) || stripos($callerFile, $docRoot) === false) {
                    return false;
                }
            }
            unset($callerFile, $trace);
        }
        unset($traces);
    }
    unset($docRoot);

    return true;
}

如果 运行 通过 CLI 或没有 DOCUMENT_ROOT 值的东西,上面的功能将不起作用。 阅读更多关于 $_SERVER

如果我有这样的文件...

/var/www/public_html/run.php
/var/www/test.php
/var/www/functions.php <- 上面的函数在这个文件中。

而public目录是/var/www/public_html

require dirname(__DIR__) . '/functions.php';



var_dump(isInPublicDir());// expect true
var_dump(isInPublicDir(false));// expect true


require dirname(__DIR__) . '/test.php';

run.php 内容。

.

<?php



echo 'hello from ' . __FILE__ . '<br>' . PHP_EOL;

var_dump(isInPublicDir());// expect **false**
var_dump(isInPublicDir(false));// expect true

test.php 内容。

根据 iazaran 的 回复,这段代码对我有用!

if (strpos(getcwd(), 'public_html') !== false) {
  $page_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $ip_address = $_SERVER['REMOTE_ADDR'];
}

我认为它可能对像我这样的人有用。