【问题标题】:Can I count on the availability of $_SERVER['SCRIPT_FILENAME']?我可以指望 $_SERVER['SCRIPT_FILENAME'] 的可用性吗?
【发布时间】:2015-03-10 21:52:43
【问题描述】:

我正在编写一个网络应用程序,并且想使用 $_SERVER['SCRIPT_FILENAME'] 来做一些事情。如果真的有必要,我可以为该任务使用更简单但更手动(需要一些硬编码)的方法。 (几乎)所有或大多数 Web 服务器中的该变量是否始终可用?指望它是否明智?

我问这个是因为在过去的某个时候,我从一些人那里听说,一些 $_SERVER 变量可能没有在相当多的环境/Web 服务器/操作系统/...中设置,我想我已经读过这方面的信息在一些更可靠的来源。

【问题讨论】:

    标签: php environment-variables superglobals


    【解决方案1】:

    我更喜欢__FILE__,因为它更容易打字和阅读。

    PHP 对于确定当前脚本文件名的两种方式都有奇怪的行为。我基于此脚本的输出:

    var_dump(__FILE__);
    var_dump($_SERVER['SCRIPT_FILENAME']);
    var_dump(realpath(__FILE__));
    var_dump(realpath($_SERVER['SCRIPT_FILENAME']));
    

    PHP 5.6 命令行、Windows、Cygwin:

    string(40) "/cygdrive/c/file.php"
    string(8) "file.php"
    string(40) "/cygdrive/c/file.php"
    string(40) "/cygdrive/c/file.php"
    

    PHP 5.6 命令行、Windows、cmd:

    string(31) "C:\file.php"
    string(8) "file.php"
    string(31) "C:\file.php"
    string(31) "C:\file.php"
    

    Apache + PHP 5.6,Windows:

    string(31) "C:\file.php"
    string(31) "C:/file.php"
    string(31) "C:\file.php"
    string(31) "C:\file.php"
    

    PHP 5.4 命令行,Linux:

    string(35) "/var/www/blah/file.php"
    string(8) "file.php"
    string(35) "/var/www/blah/file.php"
    string(35) "/var/www/blah/file.php"
    

    Nginx + PHP 5.4,Linux:

    string(35) "/var/www/blah/file.php"
    string(35) "/var/www/blah/file.php"
    string(35) "/var/www/blah/file.php"
    string(35) "/var/www/blah/file.php"
    

    所以你必须根据你的情况来看看哪个是最好的。 :-)

    【讨论】:

      【解决方案2】:

      为此,我建议 __FILE__ 如果您使用 php 自己的 Magic constants 之一,您可以确定它可以跨平台工作

      【讨论】:

      • 谢谢你,但由于某些原因我不能使用诸如 FILE 之类的东西。我也不关心 CLI,只关心 Web 环境。我感兴趣/只需要知道 SCRIPT_FILENAME 的可用性。我的意思是我可以确定如果我使用它,我的应用程序将在所有主要 Web 服务器操作系统(Linux、Windows、BSD 等)上的所有主要 Web 服务器软件中运行。
      • 无法帮助您解决任意限制
      猜你喜欢
      • 2010-12-24
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多