What are some best practices for handling user input and external requests in PHP scripts to prevent malicious activity?
Issue: To prevent malicious activity, it is important to sanitize and validate user input and properly handle external requests in PHP scripts. This can help prevent SQL injection, cross-site scripting (XSS), and other security vulnerabilities. PHP Code Snippet:
// Sanitize and validate user input
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);
if (!$user_input) {
die("Invalid input");
}
// Handle external requests securely
$external_url = 'https://example.com/api/data';
$response = file_get_contents($external_url);
if ($response === false) {
die("Error fetching external data");
}
// Process the response
$data = json_decode($response, true);
if ($data === null) {
die("Error decoding JSON data");
}
// Use the data safely in your script
foreach ($data as $item) {
echo $item['name'];
}