要确保PHP HTML代码的安全性,可以采取以下措施:
htmlspecialchars()
、htmlentities()
或strip_tags()
函数来实现这一目的。$user_input = $_POST['user_input'];
$safe_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
// 使用PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$username = $_POST['username'];
$email = $_POST['email'];
$stmt->execute();
// 使用MySQLi
$mysqli = new mysqli('localhost', 'username', 'password', 'mydb');
$stmt = $mysqli->prepare('INSERT INTO users (username, email) VALUES (?, ?)');
$stmt->bind_param('ss', $username, $email);
$username = $_POST['username'];
$email = $_POST['email'];
$stmt->execute();
header('Content-Security-Policy: default-src "self"; script-src "self" https://trustedscripts.example.com; style-src "self" https://trustedstyles.example.com; img-src "self" data:');
session_start()
函数启动会话,设置安全的会话cookie选项,以及使用rand()
或mt_rand()
函数生成安全的会话ID。session_start();
// 设置安全的会话cookie选项
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
// 生成安全的会话ID
$secure_session_id = bin2hex(random_bytes(32));