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

PHP 升級後報錯「set_magic_quotes_runtime is deprecated」的解決辦法

     編輯:PHP 相關知識

錯誤原因

set_magic_quotes_runtime() 自 PHP 5.3 起**棄用**,PHP 7.0 **完全移除**。舊代碼調用會拋出 Deprecated 或 Fatal error。

官方替代方案

<?php
// 舊代碼
set_magic_quotes_runtime(0);

// 替代:運行時設置 ini
ini_set('magic_quotes_runtime', '0');

// 或 php.ini 永久生效
; magic_quotes_runtime = Off

背景知識:Magic Quotes 是什麼?

  • PHP 早期特性:自動對 GET/POST/COOKIE 數據轉義引號 (' → \', " → \", \ → \\, NULL → \0)。
  • **極其惡劣的設計**:導致數據重複轉義、編碼問題、安全幻覺、可移植性差。
  • PHP 5.4 **完全移除** magic_quotes 相關功能。

徹底清理遺留代碼

  1. 搜尋項目:grep -r "magic_quotes" --include="*.php" .
  2. 替換所有 set_magic_quotes_runtime 為 ini_set('magic_quotes_runtime', 0) 或直接刪除(PHP 5.4+ 無效)。
  3. 檢查 get_magic_quotes_gpc() 判斷邏輯,現代代碼**直接假設關閉**處理。

現代輸入處理最佳實踐

<?php
// 1. 數據庫:使用預處理語句 (PDO/MySQLi)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$_POST['email']]); // 無需手動轉義

// 2. HTML 輸出:htmlspecialchars
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// 3. Shell 命令:escapeshellarg/escapeshellcmd
$cmd = 'ls ' . escapeshellarg($filename);

// 4. JSON:json_encode 自動處理
echo json_encode($data);

// 5. 正則:preg_quote
$pattern = '/' . preg_quote($keyword, '/') . '/';
?>

遷移檢查清單

  • [ ] 刪除所有 set_magic_quotes_runtime 調用。
  • [ ] 移除 get_magic_quotes_gpc 相關判斷分支。
  • [ ] 確認數據庫層使用預處理,無手動 addslashes/stripslashes。
  • [ ] 確認輸出層統一使用 htmlspecialchars (HTML) / json_encode (API)。
  • [ ] 測試包含引號、反斜杠、NULL 字符的輸入數據。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved