要確保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));