This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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:

  1. HTTP Status Codes
  2. The code below.

For example, the following code determines the status code of a URL using cURL:

 * 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);
  	return (404 !== $httpCode);


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.


I'm a Senior Backend Engineer at WebDevStudios and I can often be found of software engineering within the context of blogging on my own site.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.