What are the best practices for handling IP address validation and comparison in PHP scripts?

When validating and comparing IP addresses in PHP scripts, it is important to use built-in functions like filter_var() with the FILTER_VALIDATE_IP flag to ensure the IP address format is correct. Additionally, when comparing IP addresses, it is recommended to use the inet_pton() function to convert IP addresses to binary format for accurate comparison.

// Validate an IP address
$ip = '192.168.1.1';
if (filter_var($ip, FILTER_VALIDATE_IP)) {
    echo 'Valid IP address';
} else {
    echo 'Invalid IP address';
}

// Compare two IP addresses
$ip1 = '192.168.1.1';
$ip2 = '192.168.1.2';
if (inet_pton($ip1) == inet_pton($ip2)) {
    echo 'IP addresses are the same';
} else {
    echo 'IP addresses are different';
}