What are the best practices for handling IP addresses in PHP to ensure accuracy and security?

When handling IP addresses in PHP, it is important to validate and sanitize user input to ensure accuracy and prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to achieve this is by using PHP's filter_var() function with the FILTER_VALIDATE_IP filter option. This function will validate the IP address format and return false if the input is not a valid IP address.

// Validate and sanitize user input for IP address
$ip = filter_var($_POST['ip'], FILTER_VALIDATE_IP);

if($ip === false){
    // Handle invalid IP address input
    echo "Invalid IP address";
} else {
    // Proceed with using the validated IP address
    echo "Valid IP address: " . $ip;
}