在命令列執行 PHP 腳本時,工作目錄預設為 php.exe 所在目錄,導致相對路徑無法正確定位檔案。本文提供兩種通用解決方案,適用於手動執行與 Crontab 定時任務。
<?php
// 測試腳本
echo "原始工作目錄: " . getcwd() . "\n"; // 顯示 php.exe 目錄
$fp = fopen("data.txt", "w"); // 會在 php.exe 目錄建立檔案
fwrite($fp, "test");
fclose($fp);
?>
<?php
$oldPath = getcwd();
$scriptDir = dirname(__FILE__); // 或 __DIR__ (PHP 5.3+)
chdir($scriptDir); // 切換至腳本所在目錄
echo "新工作目錄: " . getcwd() . "\n";
$fp = fopen("data.txt", "w"); // 現在在腳本目錄建立
fwrite($fp, "test");
fclose($fp);
chdir($oldPath); // 可選:恢復原目錄
?>
<?php
$scriptDir = dirname(__FILE__);
$currentIncludePath = ini_get('include_path');
ini_set('include_path', $scriptDir . PATH_SEPARATOR . $currentIncludePath);
// 現在可以用相對路徑 require
require_once 'config.php';
require_once 'lib/database.php';
?>
# 失敗範例:相對路徑 require 失敗 * * * * * /usr/bin/php /var/www/html/task/run.php # 成功範例:在腳本開頭加入 chdir * * * * * /usr/bin/php /var/www/html/task/run.php # run.php 內容 <?php chdir(dirname(__FILE__)); require_once '../config.php'; // ... 後續邏輯 ?>
getcwd() 取得當前工作目錄(CLI 下為 PHP 執行檔目錄)__FILE__ / __DIR__ 取得目前腳本絕對路徑chdir() 切換工作目錄,影響後續相對路徑解析