Using cURL to Determine the Status Code of a URL
Whenever we’re working with remote requests within WordPress, we’re likely using one of the functions that are available through the core API. These are functions such as:
And they’re great and I recommend using them.
Depending on the project, you may need to determine the HTTP status of the page before making the request. And if you want to do that, I recommend two things:
- HTTP Status Codes
- The code below.
For example, the following code determines the status code of a URL using cURL:
<?php
/**
* Determines if a specific URL returns a valid page. This is experimental and it is based on
* the status code.
*
* @param string $url the url to evaluate
*
* @return bool true if the URL returns a status code of 404; otherwise, false
*/
public function isValidUrl(string $url): bool
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return (404 !== $httpCode);
}
@source: https://gist.github.com/tommcfarlin/2ad96af9aa3007807686ac87b630dcd7#file-00-is-valid-url-php
Of course, you can replace 404 with any value from the above page to evaluate it to any given status you need.
Regardless, before making a request to a given URL, this particular function can help you determine the course of action you need to take in your project before actually making a request and have it fail.