定义
__FILE__
是一个魔法变量(预定义常量),当前运行文件的完整路径(真是文件路径,非软链路径)和文件名。如果用在被包含文件中,则返回被包含的文件名。
官方解释:
__FILE__ | 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。 |
由于软链接路径导致问题case 参考:
PHP魔术常量__FILE__无法识别符号链接问题解决 :http://www.kaijia.me/2012/08/linux-apache-use-symlink-and-permission-issue-solved/
How do you get PHP, Symlinks and __FILE__ to work together nicely? :http://stackoverflow.com/questions/3221771/how-do-you-get-php-symlinks-and-file-to-work-together-nicely
示例
环境:
apache 根目录:/usr/local/apache/htdocs
在/usr/local/apache/htdocs 下
有文件夹
test
软链接
symbol -> test
在test目录下有文件file.php
php echo __FILE__."\n"; echo dirname(__FILE__)."\n"; print_r($_SERVER);
浏览器运行:http://192.168.44.129/symbol/file.php
返回:
/usr/local/services/httpd-2.2.21/htdocs/test/file.php /usr/local/services/httpd-2.2.21/htdocs/test Array ( [HTTP_HOST] => 192.168.44.129 [HTTP_CONNECTION] => keep-alive [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36 [HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4 [PATH] => /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/php/bin:/root/bin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/1.0.1h PHP/5.3.28 [SERVER_NAME] => 192.168.44.129 [SERVER_ADDR] => 192.168.44.129 [SERVER_PORT] => 80 [REMOTE_ADDR] => 192.168.44.1 [DOCUMENT_ROOT] => /usr/local/services/httpd-2.2.21/htdocs [SERVER_ADMIN] => [email protected] [SCRIPT_FILENAME] => /usr/local/services/httpd-2.2.21/htdocs/symbol/file.php [REMOTE_PORT] => 59738 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /symbol/file.php [SCRIPT_NAME] => /symbol/file.php [PHP_SELF] => /symbol/file.php [REQUEST_TIME] => 1422894434 )
结论:
__FILE__ 获取到的是文件的绝对路径,如果是符号链接则是解析后的绝对路径
$_SERVER['SCRIPT_FILENAME'] 获取当前执行脚本的绝对路径,不解析符号链接