首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP.ini 配置錯誤導致的兩大經典報錯:上傳臨時目錄與 exec 函數禁用

     編輯:PHP 相關知識

PHP.ini 配置錯誤導致的兩大經典報錯:上傳臨時目錄與 exec 函數禁用

實戰中常遇到的兩個由 php.ini 配置不當引發的報錯:AJAX 圖片上傳「無法創建臨時文件」與 exec() 壓縮資源失效。本文提供根因分析與 Windows/Linux 雙平台修復方案。

案例一:文件上傳報錯 File upload error - unable to create a temporary file

根因

upload_tmp_dir 未設置或指向的目錄無寫入權限,PHP 退回系統默認臨時目錄(如 C:\Windows\Temp 或 /tmp),但進程用戶(IIS_IUSRS / www-data / nginx)無權限讀寫。

修復步驟

  1. 啟用並指定專用目錄
    編輯 php.ini:
    upload_tmp_dir = "D:/php/tmp" (Windows)
    upload_tmp_dir = "/var/www/php_tmp" (Linux)
  2. 創建目錄並授權
    Windows:右鍵目錄 → 安全 → 編輯 → 添加 IIS_IUSRS / IUSR → 勾選「讀取/寫入/修改」。
    Linux:mkdir -p /var/www/php_tmp && chown www-data:www-data /var/www/php_tmp && chmod 755 /var/www/php_tmp
  3. 重啟 PHP-FPM / Apache / IIS 使配置生效。

案例二:exec() / shell_exec() 被禁用導致前端資源壓縮失敗

現象

代碼邏輯、權限均正常,但調用 exec('uglifyjs ...') 無輸出、無報錯,實際被 disable_functions 截斷。

修復步驟

  1. 修改 php.ini 解禁函數
    搜索 disable_functions,移除 exec、shell_exec、passthru、proc_open 等:
    disable_functions = "pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,"
    注意:生產環境建議僅解禁必要函數,並配合 open_basedir 限制執行路徑。
  2. Windows 下授權 cmd.exe
    C:\Windows\System32\cmd.exe → 右鍵屬性 → 安全 → 編輯 → 添加 IIS_IUSRS / IUSR → 勾選「讀取與執行」「讀取」。
  3. Linux 無需額外授權,確保 PHP-FPM 進程用戶擁有調用二進制文件(如 /usr/bin/uglifyjs)的執行權限即可。
  4. 重啟服務驗證:php -r "exec('echo test', \$o); var_dump(\$o);" 應輸出 array(1) { [0]=> string(4) "test" }。

安全加固建議

  • 禁用 exec 系函數是基線安全要求,若業務必須調用外部命令,優先考慮:
    ① 使用 PHP 原生擴展(如 imagick 替代 convert、ZipArchive 替代 zip)。
    ② 引入任務隊列(RabbitMQ/Redis Stream),由獨立 Worker 進程(受限容器/沙箱)執行命令,Web 進程僅發送任務。
    ③ 啟用 open_basedir 限制可讀寫目錄,結合 disable_functions 最小化攻擊面。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved