php命令行(cli)下執(zhí)行PHP腳本文件的相對路徑的問題解決方法
在php命令行下執(zhí)行.php文件時,執(zhí)行環(huán)境的工作目錄(getcwd( ))是php命令程序(php.exe)所在目錄,所以如果想在文件內(nèi)使用相對路徑時,要先切換當前的工作目錄才行。
小測試程序:
<?php
$oldpath = getcwd(); // 原始工作目錄 php.exe所在目錄
$path = dirname(__FILE__);
chdir($path); // 切換工作目錄為當前文件所在目錄
$fpath = "forum/readme.txt";
$fp = fopen($fpath, "a+b"); // 如果不切換工作目錄這里會報找不到文件的錯誤
fwrite($fp, "oldpath:".$oldpath."-newpath:".getcwd());
fclose($fp);
?>
需要用crotab定時執(zhí)行的程序也會有這下問題??梢詤⒖枷旅孢@篇文章:
使用php腳本寫了一個腳本,需要在crontab中定期運行,但是出現(xiàn)如下錯誤
代碼如下:
/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)
...............
運行失敗
嘗試解決方法2 加入如下代碼
復制代碼代碼如下:
$cur_dir = dirname(__FILE__);
chdir($cur_dir);
require(../class/a.php)
require(../class/b.php)
運行成功
總結: 在require 時,如果是相對目錄,在crontab 中運行php腳本,要進入到腳本所在目錄才可以
相關文章
PHP Class self 與 static 異同與使用詳解
這篇文章主要介紹了PHP中 Class self 與 static 有什么區(qū)別,都怎么用,需要的朋友們下面隨著小編來一起學習學習吧2021-09-09PHP實現(xiàn)對png圖像進行縮放的方法(支持透明背景)
這篇文章主要介紹了PHP實現(xiàn)對png圖像進行縮放的方法(支持透明背景),可實現(xiàn)php針對png圖像的縮放功能,且支持透明背景,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07php5.3 不支持 session_register() 此函數(shù)已啟用的解決方法
php從5.2.x升級到5.3.2.出來問題了。有些原來能用的程序報錯了,Deprecated: Function session_register() is deprecated2013-11-11PHP連接及操作PostgreSQL數(shù)據(jù)庫的方法詳解
這篇文章主要介紹了PHP連接及操作PostgreSQL數(shù)據(jù)庫的方法,結合實例形式分析了php針對PostgreSQL數(shù)據(jù)庫的基本連接以及增刪改查等相關操作技巧,需要的朋友可以參考下2019-01-01