What steps can be taken to prevent unauthorized access or malicious code injection when using URL variables in PHP?

To prevent unauthorized access or malicious code injection when using URL variables in PHP, you should always sanitize and validate the input before using it in your code. This can be done by using functions like filter_input() or htmlspecialchars() to clean the input and make it safe for use.

// Sanitize and validate URL variable input
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

// Use the sanitized variable in your code
if ($id) {
    // Perform actions using the sanitized $id variable
    echo "ID: " . $id;
} else {
    // Handle invalid input or unauthorized access
    echo "Invalid ID";
}