Check if URL exist PHP

For check if URL exist PHP. Here we use cURL which is accurate compare to other method like get_headers.

Check if URL exist PHP
Check if URL exist PHP

Here suggest cURL for check if URL exists or not. get_headers gives 404 Not Found or different response code if URL have redirection.

Before use check valid URL process on server side, need to consider some points that help to select method.

Check if URL exist PHP process points to attention

  • User enter URL or it comes from any source
  • URL check Process waiting for response, might take time and block code execution, for safety you can use timeout
  • sometime it possible response comes 200 but other redirection exists using JavaScript etc.,
  • Request only for header not full body/content

Keep in mind that whatever method you use, it takes time to wait for a response. All code might (and probably will) halt until you either know the result or the requests timed out.

function urlExist($url){
    $ch = @curl_init($url);

    @curl_setopt($ch, CURLOPT_HEADER, true);// we want headers
    @curl_setopt($ch, CURLOPT_NOBODY, true);// dont need body
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// catch output (do NOT print!)
    //@curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); // in case ignore ssl certification process
    //@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //@curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);// max connection time
    //@curl_setopt($ch, CURLOPT_TIMEOUT, 5); // max response time

    if(@curl_errno($ch)){// should be 0
        return false;

    $code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);// get response code
    return $code == 200 ? true : false;

if(urlExist('')) {
    echo 'Valid URL';
} else {
    echo 'Invalid URL';