Hillcow
Hillcow

Reputation: 979

PHP: Get hostname of external website by URL (determine if the hostname includes 'www')

Given I have an URL to an external website like `https://www.test.com' or 'https://test.com', but I'm not sure if the hostname of the external website actually includes 'www' or not. How can I determine this using PHP?

Upvotes: 0

Views: 187

Answers (1)

TheGentleman
TheGentleman

Reputation: 2362

You want to call the URL and check the status headers. Curl does this pretty well. Something like this should work.

$url = "https://test.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY,  true);
curl_setopt($ch, FOLLOW_LOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_exec($ch);

$returnCode = curl_getinfo($ch,CURLINFO_HTTP_CODE); //200 = success, 4xx/5xx = error
if ($returnCode === 200) { //The url resolved and loaded
   //Do Stuff Here
} else if($returnCode === 301) { //The url resolved but forwarded to a different url        
    $effectiveURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); //The effective URL will be the final url in the chain (e.g. if www.test.com forwarded to test.com)
}
curl_close($ch);

That snippet will check if a URL exists and can be resolved successfully. It will also account for cases where the domain forwarded to another domain. You'll definitely need to wrap this in some more checking/logic (look into FILTER_VALIDATE_URL) but this should get you started with the concept. You'll also probably want to adjust your timeout values to fit the specifics of your use case.

Upvotes: 1

Related Questions