PHP Code to Check URL HTTP Status Code

php http status codecurl getinfophp url checkhttp response codecurl_setopt
Published·Modified·
/**
 * Returns the HTTP status code
 * 
 * @param string $url
 * @return string
 */
public function get_http_code($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url); // Set URL
    curl_setopt($curl, CURLOPT_HEADER, 1); // Get Header
    curl_setopt($curl, CURLOPT_NOBODY, true); // No Body needed, we only need the Head
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // Store data as a string instead of outputting directly
    $data = curl_exec($curl); // Execute
    $return = curl_getinfo($curl, CURLINFO_HTTP_CODE); // Get HTTP status code
    
    curl_close($curl); // Close the connection
    
    return $return;
}