การทำความสะอาดข้อมูลนำเข้า (Sanitizing) เป็นแนวคิดสำคัญใน PHP Sanitizing หมายถึงการ escape ตัวอักษรที่ไม่ได้รับอนุญาตในข้อมูลนำเข้า มาดูแนวทางปฏิบัติที่ดีที่สุดสำหรับการประมวลผลข้อมูลอย่างปลอดภัย
การใช้ real_escape_string() ในคำสั่ง mysqli
ตัวอย่าง
<?php
$conn = new mysqli("localhost", "root", "", "testdb");
$street = $conn->real_escape_string($_POST['street']);
?>
ใช้ htmlentities() และ html_entity_decode() เมื่อบันทึกลงฐานข้อมูลและแสดงในเบราว์เซอร์
ตัวอย่าง
<?php $data['message'] = htmlentities($message); // เวลาบันทึกลงฐานข้อมูล echo html_entity_decode($data['message']); // เวลาแสดงในเบราว์เซอร์ ?>
Sanitize user-input สำหรับ Command Prompt ด้วย escapeshellarg
ตัวอย่าง
<?php
system('ls '.escapeshellarg($data['dir']));
?>