php 命令执行脚本文件路径,php命令行(cli)下执行PHP脚本文件的相对路径的问题解决方法...
在php命令行下執(zhí)行.php文件時(shí),執(zhí)行環(huán)境的工作目錄(getcwd( ))是php命令程序(php.exe)所在目錄,所以如果想在文件內(nèi)使用相對(duì)路徑時(shí),要先切換當(dāng)前的工作目錄才行。
小測(cè)試程序:
$oldpath = getcwd(); // 原始工作目錄 php.exe所在目錄
$path = dirname(__FILE__);
chdir($path); // 切換工作目錄為當(dāng)前文件所在目錄
$fpath = "forum/readme.txt";
$fp = fopen($fpath, "a+b"); // 如果不切換工作目錄這里會(huì)報(bào)找不到文件的錯(cuò)誤
fwrite($fp, "oldpath:".$oldpath."-newpath:".getcwd());
fclose($fp);
?>
需要用crotab定時(shí)執(zhí)行的程序也會(huì)有這下問題。可以參考下面這篇文章:
使用php腳本寫了一個(gè)腳本,需要在crontab中定期運(yùn)行,但是出現(xiàn)如下錯(cuò)誤
代碼如下:
/var/www/html/bt/e/BtSys:.:/usr/share/pear:/usr/share/phpPHP Warning: require(../class/connect.php): failed to open stream: No such file or directory in /var/www/html/bt/e/BtSys/torrents-scrape.php on line 17
PHP Fatal error: require(): Failed opening required '../class/connect.php' (include_path='/var/www/html/bt/e/BtSys:.:/usr/share/pear:/usr/share/php') in /var/www/html/bt/e/BtSys/torrents-scrape.php on line 17
嘗試解決方法1 加入如下代碼
// setting include path
$cur_dir=getcwd();
$cur_dir=$basedir = dirname(__FILE__);
$path = ini_get('include_path');
ini_set("include_path", "$cur_dir:$path");
$path = ini_get('include_path');
//echo $path;
require(../class/a.php)
require(../class/b.php)
...............
運(yùn)行失敗
嘗試解決方法2 加入如下代碼
復(fù)制代碼代碼如下:
$cur_dir = dirname(__FILE__);
chdir($cur_dir);
require(../class/a.php)
require(../class/b.php)
運(yùn)行成功
總結(jié): 在require 時(shí),如果是相對(duì)目錄,在crontab 中運(yùn)行php腳本,要進(jìn)入到腳本所在目錄才可以
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的php 命令执行脚本文件路径,php命令行(cli)下执行PHP脚本文件的相对路径的问题解决方法...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php发送gmail,使用GMail S
- 下一篇: php 算法 数字比较,数据两两比较的高