Sunday, July 10, 2022

[SOLVED] I want to check if a site is alive within this cURL code?

Issue

I use this code to get a response/result from the other server and I want to know how can I check if the site is alive?

$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php

Solution

All you really have to do is a HEAD request to see if you get a 200 OK message after redirects. You do not need to do a full body request for this. In fact, you simply shouldn't.

function check_alive($url, $timeout = 10) {
  $ch = curl_init($url);

  // Set request options
  curl_setopt_array($ch, array(
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_NOBODY => true,
    CURLOPT_TIMEOUT => $timeout,
    CURLOPT_USERAGENT => "page-check/1.0" 
  ));

  // Execute request
  curl_exec($ch);

  // Check if an error occurred
  if(curl_errno($ch)) {
    curl_close($ch);
    return false;
  }

  // Get HTTP response code
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  // Page is alive if 200 OK is received
  return $code === 200;
}


Answered By - Andrew Moore
Answer Checked By - Gilberto Lyons (WPSolving Admin)