为了防止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输出受到攻击。