Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

curl

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
like image 768
Ahmad Fouad Avatar asked Jun 30 '11 22:06

Ahmad Fouad


People also ask

How to check url status using cURL in Windows?

How to Check URL Status Using CURL? In this post, I am giving an example of how to check the URL status using CURL command in Windows. In Windows, open the command prompt and type the following command to check the URL resource: Replace http://<your_URL> with the URL you want to test.

How do I check if a file exists in curl?

It starts with Curl making a HEAD request and then pipes the returned headers through to grep. Grep, using a regular expression, extracts the response code header and pipes it to awk. Awk then extracts the response number. Finally, if the response code is 200, then “ file exists ” is echoed to the terminal. Cheeky book promotion.

How do I check if a URL is valid or not?

Check URL Using CURL Command Example. In Windows, open the command prompt and type the following command to check the URL resource: curl -svo /dev/null http://<your_URL> Replace http://<your_URL> with the URL you want to test. For example:

How to check if a website is alive or not?

I think that for the simplest way to check if the site is alive, you could use the following method: This will return HTTP/1.1 200 OK. If the return doesn't match your output then call out for help. Show activity on this post.


1 Answers

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;
}
like image 129
Andrew Moore Avatar answered Sep 28 '22 14:09

Andrew Moore