Check If Website Is Down Using PHP And Curl

Checking website if down through PHP ,OOP and curl, is very easy, With a few lines of codes you can make a website checker script that can check the websites if down and show you with frame, So in this tutorial you learn how to create a website checker so let's start

Check If Website Is Down Using PHP And Curl



NOTE:Demo might be slow or will be not work because it's hosted on free hosting site 
Check If Website Is Down Using PHP And Curl
Demo


This is our main function class

<?php 
 class Main{
  public function site($url){
   //Initializes a new cURL session 
   $url = curl_init($url);
   //Sets an option on the given cURL session handle.
   curl_setopt($url, CURLOPT_NOBODY, true);
   // follow any "Location: " header that the server sends as part of the HTTP header 
   curl_setopt($url, CURLOPT_FOLLOWLOCATION, true);
   // Execute the given cURL session. 
   curl_exec($url);
   // Gets information about the last transfer. 
   $status = curl_getinfo($url, CURLINFO_HTTP_CODE);
   //return the status code if status code is 200 that's mean the site is Up
   return ($status == 200) ? true : false;
   }
}
?>
index.php:

<?php
//inclute the main class
include 'main.php';
//instantiation the class
$check = new Main; 
 //User submit url
if(isset($_POST['submit'])){
    //trim the url
    $url = trim($_POST['url']);
   //Add http to url if not have
   if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }  
   //Validate the url 
    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
        //check website  
        $check->site($url);
    } else {
        echo("$url is not a valid URL");
    }
}     
<!DOCTYPE html>
<html>
<head>
 <title>Check Website Is Up Or Down - meralesson.com</title>
 <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="wrapper">
  <div class="header">
  <form method="post">
    <ul>
      <li>
        <input type="text"  autocomplete="off" class="search" name="url" placeholder="http://">
      </li>
      <li>
        <input type="submit" name="submit" class="button"  value="Search" />
      </li>
    </ul>
    </form>
    <div class="right-div">
      <h2>{Website Checker}</h2>
    </div>
  </div>
  <div class="content">
    <iframe src="<?php if(isset($url)){echo $url;}?>">
      <p>Your browser does not support iframes.</p>
    </iframe>
  </div>
</div>
</body>
</html>
?>

Comments