【背景】
折腾:
期间,为了自动生成log文件,想要获得当前PHP脚本的路径和文件名。
【折腾过程】
1.其实关于PHP脚本文件名已经知道了:
$scriptName = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
不过发现是当前PHP文件的调用者的信息,而不是当前PHP文件本身的信息。
2.去搜:
php current php file path
参考:
好像直接用getcwd就可以了?
3.php – Get absolute path of current script – Stack Overflow
中说的__FILE__好像是我此处所需要的。
去试试,最终获得了对应的所需要的内容:
//logFolder=/var/www/1.2.3.4/public_html/php/access_token $logFolder = getcwd(); //logFilename=log_20150727131103.log $logFilename = "log_".date('YmdHis').".log"; //defautLogFile=/var/www/1.2.3.4/public_html/php/access_token/log_20150727131103.log $defautLogFile = $this->concatenatePath($logFolder, $logFilename); /* * 【已解决】PHP中如何实现路径拼接(两个路径合并)以及合并文件夹路径和文件名 * https://www.crifan.com/php_path_concatenation_combine_directory_and_filename * eg: * from: * D:\tmp\WordPress\DevRoot\httpd-2.2.19-win64\httpd-2.2-x64\htdocs\php_test\35934503_data * cookie_jar.txt * to: * D:\tmp\WordPress\DevRoot\httpd-2.2.19-win64\httpd-2.2-x64\htdocs\php_test\35934503_data\cookie_jar.txt */ function concatenatePath($headPath, $tailPath) { $realHeadPath = realpath($headPath); // printAutoNewline("realHeadPath=".$realHeadPath); //$realTailPath = realpath($tailPath); //printAutoNewline("realTailPath=".$realTailPath); //$concatnatedPath = $realHeadPath.DIRECTORY_SEPARATOR.$realTailPath; // printAutoNewline("tailPath=".$tailPath); $concatnatedPath = $realHeadPath.DIRECTORY_SEPARATOR.$tailPath; // printAutoNewline("concatnatedPath=".$concatnatedPath); return $concatnatedPath; }
【总结】
PHP中,获得当前的路径/文件夹可以用:
- getcwd()
- dirname(__FILE__)
- basename(__DIR__)
转载请注明:在路上 » 【已解决】PHP中如何获得当前PHP文件的路径