php命令行(cli)下執(zhí)行PHP腳本文件的相對(duì)路徑的問題解決方法
在php命令行下執(zhí)行.php文件時(shí),執(zhí)行環(huán)境的工作目錄(getcwd( ))是php命令程序(php.exe)所在目錄,所以如果想在文件內(nèi)使用相對(duì)路徑時(shí),要先切換當(dāng)前的工作目錄才行。
小測(cè)試程序:
<?php
$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)入到腳本所在目錄才可以
相關(guān)文章
php生成二維碼時(shí)出現(xiàn)中文亂碼的解決方法
這篇文章主要介紹了php生成二維碼時(shí)出現(xiàn)中文亂碼的解決方法,較為詳細(xì)的分析了php生成二維碼的方法,以及出現(xiàn)亂碼時(shí)的解決方法,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2014-12-12PHP Class self 與 static 異同與使用詳解
這篇文章主要介紹了PHP中 Class self 與 static 有什么區(qū)別,都怎么用,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-09-09PHP實(shí)現(xiàn)對(duì)png圖像進(jìn)行縮放的方法(支持透明背景)
這篇文章主要介紹了PHP實(shí)現(xiàn)對(duì)png圖像進(jìn)行縮放的方法(支持透明背景),可實(shí)現(xiàn)php針對(duì)png圖像的縮放功能,且支持透明背景,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07php5.3 不支持 session_register() 此函數(shù)已啟用的解決方法
php從5.2.x升級(jí)到5.3.2.出來問題了。有些原來能用的程序報(bào)錯(cuò)了,Deprecated: Function session_register() is deprecated2013-11-11PHP連接及操作PostgreSQL數(shù)據(jù)庫的方法詳解
這篇文章主要介紹了PHP連接及操作PostgreSQL數(shù)據(jù)庫的方法,結(jié)合實(shí)例形式分析了php針對(duì)PostgreSQL數(shù)據(jù)庫的基本連接以及增刪改查等相關(guān)操作技巧,需要的朋友可以參考下2019-01-01