In what scenarios would using fsockopen() be more suitable for validating URL syntax compared to other methods in PHP?

Using fsockopen() can be more suitable for validating URL syntax in scenarios where you need to check if a URL is reachable or if a specific resource exists on a remote server. This function allows you to establish a connection to the server specified in the URL and check for any response, making it a more robust method for URL validation compared to simpler methods like using regular expressions.

$url = 'https://www.example.com';

$parts = parse_url($url);

if(isset($parts['scheme']) && isset($parts['host'])) {
    $fp = @fsockopen($parts['host'], 80, $errno, $errstr, 5);
    
    if($fp) {
        echo 'URL is valid and reachable.';
        fclose($fp);
    } else {
        echo 'URL is not reachable.';
    }
} else {
    echo 'Invalid URL syntax.';
}