How can one ensure proper data validation and sanitization when working with JSON in PHP?
To ensure proper data validation and sanitization when working with JSON in PHP, one can use functions like json_decode() to validate the incoming JSON data and filter_var() or htmlentities() to sanitize the data before using it in the application.
// Validate and sanitize JSON data
$jsonData = '{"name": "<script>alert(\'XSS Attack\')</script>", "age": 25}';
$decodedData = json_decode($jsonData, true);
if ($decodedData !== null) {
$name = filter_var($decodedData['name'], FILTER_SANITIZE_STRING);
$age = filter_var($decodedData['age'], FILTER_SANITIZE_NUMBER_INT);
// Use the sanitized data in the application
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
} else {
echo "Invalid JSON data";
}