DEV Community

Derek Nguyen
Derek Nguyen

Posted on

How To Check URL Is Working Or Not In Programing Languages?

Ruby

require 'net/http'
require 'open-uri'

def working_url?(url_str)
  url = URI.parse(url_str)
  Net::HTTP.start(url.host, url.port) do |http|
    http.head(url.request_uri).code == '200'
  end
rescue
  false
end
Enter fullscreen mode Exit fullscreen mode

PHP

$url = "http://www.domain.com/demo.jpg";
$headers = @get_headers($url);
if(strpos($headers[0],'404') === false)
{
  echo "URL Exists";
}
else
{
  echo "URL Not Exists";
}
Enter fullscreen mode Exit fullscreen mode

Python

from urllib2 import urlopen
code = urlopen("https://kipalog.com").code
if code == 200:
   print "Exists!"


# Or

import urllib2
ret = urllib2.urlopen('https://kipalog.com')
if ret.code == 200:
    print "Exists!"
Enter fullscreen mode Exit fullscreen mode

Shell

#!/bin/bash

http_code=$(curl -I -s -o /dev/null -w "%{http_code}" "https://kipalog.com/")

if [ "$http_code" == "200" ]; then
  echo "Exist!!!"
fi
Enter fullscreen mode Exit fullscreen mode

CURL

$url = "http://www.domain.com/demo.jpg";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
if ($result !== false)
{
  $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ($statusCode == 404)
  {
    echo "URL Not Exists"
  }
  else
  {
     echo "URL Exists";
  }
}
else
{
  echo "URL not Exists";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)