為了防止PHP輸出受到攻擊,您可以采取以下措施:
filter_var()
,來清理用戶輸入。$user_input = $_POST['user_input'];
$filtered_input = filter_var($user_input, FILTER_SANITIZE_STRING);
// 使用PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->bindParam(':email', $email);
$email = $_POST['email'];
$stmt->execute();
// 使用MySQLi
$mysqli = new mysqli('localhost', 'username', 'password', 'mydb');
$stmt = $mysqli->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$email = $_POST['email'];
$stmt->execute();
htmlspecialchars()
函數進行編碼。$user_input = $_POST['user_input'];
$encoded_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $encoded_input;
header('Content-Security-Policy: default-src "self"; script-src "self" https://trustedscripts.example.com; style-src "self" https://trustedstyles.example.com;');
HttpOnly
和Secure
標志,以及定期更新會話cookie。session_start();
session_regenerate_id(true); // 強制更新會話ID
setcookie('PHPSESSID', session_id(), [
'expires' => time() + 3600, // 設置cookie過期時間
'path' => '/', // 設置cookie路徑
'domain' => $_SERVER['HTTP_HOST'], // 設置cookie域名
'secure' => true, // 僅在HTTPS連接中傳輸cookie
'httponly' => true, // 禁止客戶端JavaScript訪問cookie
]);
遵循這些最佳實踐可以幫助您防止PHP輸出受到攻擊。