Use PHP To Check Whether Remote URL, Email Or Image Link Exist

In PHP, we have a built-in function file_exist that can help us to verify whether a particular file exist in our directory. However, do you ever have the need to check whether a particular URL, email or  image link exist? We can use regular express to validate that the syntax of an email is correct but won’t it be nice to reduce the amount of spam mail received? How about those images you have on your site? Won’t you want to check whether there is a broken image or url link? Well, i have! Its always good to be informed in advance than meeting dissatisfy visitors. Anyway, in this article you will get to find and learn some of the more efficient and quicker ways to verify whether a particular link exist to use on your web application.

Check Remote Image Link Exist

There are many ways to check whether a particular image link exist after the introduce of PHP 5, GetImageSize.  GetImageSize allows us to take in a remote link to retrieve the size of the image.  Hence, we can do a simple check such as the one shown below,

1 $external_link = '';
2 if (@GetImageSize($external_link)) {
3 echo "image exists";
4 } else {
5 echo "image does not exist";
6 }

The above work well for any server that had GD installed. But there are more problem than just the one mention. This method is actually inefficient as it will download the entire image into your server before checking it. Thus, making the process very long. There might also be security risk as mention on Secure File Upload Check List that many image format allow comment  to be embedded within the image and these comment might just be some PHP code that hacker has written.  In short, this method download file from remote server to your server and take the risk of hacker using it to run malicious code after it has been downloaded on your server. BOMB! So if you are using the above method i advice you to change it and if you insist to use this, you can provide more validation checking for it. Just drop it.

So how do we check Image link in a more secure and quick environment? If you are using curl, you can try the following script:

1 function checkRemoteFile($url)
2 {
3     $ch = curl_init();
4     curl_setopt($ch, CURLOPT_URL,$url);
5     // don't download content
6     curl_setopt($ch, CURLOPT_NOBODY, 1);
7     curl_setopt($ch, CURLOPT_FAILONERROR, 1);
8     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
9     if(curl_exec($ch)!==FALSE)
10     {
11         return true;
12     }
13     else
14     {
15         return false;
16     }
17 }

Like i said, this will depend on curl. However, it is secure and quick! How about the rest of us? Lucky, PHP also provides another method called file_get_contents. file_get_contents returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE. With these in mind we can create a function to check that the file downloaded is valid by taking only 1 bytes of information from the file. Hence, whatever evil things exist on the file will only be able to run 1 byte and furthermore the function returns a string where code cannot be run. Thus, this will gives us a simple solution such as the one below,

1 function url_exists($url) {
2 if(@file_get_contents($url,0,NULL,0,1))
3 {return 1;}
4 else
5 { return 0;}
6 }

The above one is more secure than the initial one that we have and it has no dependency. The speed for this method is also faster than the initial one. But is there a faster one than the curl version?

Check For Remote URL Link

There are many ways to check whether a remote url link exist. However, checking Remote URL required the page to return certain header code to indicate that the page is successfully loaded (200). Hence, you might not want to use the method for checking image link for url link. Furthermore, For different cases you might be interested with different solution. Assuming you are just checking whether an existing domain exist, you can use the following code

1 function url_exists($url){
2     if(strstr($url, "http://")) $url = str_replace("http://", "", $url);
3     $fp = @fsockopen($url, 80);
4     if($fp === false) return false;
5     return true;
6 }

which is written by adam at darkhousemedia dot com. The above method definitely run faster than fopen but for https and domain names but for path url such as ‘′, the above won’t work although the speed is definitely one of the fastest.

Nonetheless, there are still better alternative than the one presented. We can just tried to check the header with the following code:

1 function url_exists($url){
2      if ((strpos($url, "http")) === false) $url = "http://" . $url;
3      if (is_array(@get_headers($url)))
4           return true;
5      else
6           return false;
7 }

The above work perfectly without the need to worry about complex code. However, the above method only work for HTTP and PHP 5 and above, other lower version of PHP will not. Therefore, we will need some modification on the above method to cater for lower PHP version.

1 function is_valid_url($url)
2 {
3     $url = @parse_url($url);
4     if (!$url)
5     {
6         return false;
7     }
8     $url = array_map('trim', $url);
9     $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
10     $path = (isset($url['path'])) ? $url['path'] : '';
11     if ($path == '')
12     {
13         $path = '/';
14     }
15     $path .= (isset($url['query'])) ? "?$url[query]" : '';
16     if (isset($url['host']) AND $url['host'] != gethostbyname($url['host']))
17     {
18         if (PHP_VERSION >= 5)
19         {
20             $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
21         }
22         else
23         {
24             $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
25             if (!$fp)
26             {
27                 return false;
28             }
29             fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
30             $headers = fread($fp, 4096);
31             fclose($fp);
32         }
33         $headers = (is_array($headers)) ? implode("\n", $headers) : $headers;
34         return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
35     }
36     return false;
37 }

The code here is the more detail version of the previous one which is created by SecondV on forums Dot digitalpoint Dot com. The above code cater for lower PHP version while still using the same approach of getting the return header value. Furthermore, it also validate the URL by using the parse_url method. f_open can also be used to check remote URL link.

1 function image_exist($url) {
2     if (@fclose(@fopen( $url, "r"))) {
3      // true;
4     } else {
5      // false;
6     }
7 }

However, this method required allow_url_fopen to be enabled on your php.ini file or else it will fail. Furthermore, i will not prefer this method over the previous one as it seems more sense that the page return success due to header code to indicate a success.

Check Email Exist

We can’t actually check whether a given email exist or not as it really depend on how the SMTP is being setup for each respective mail server. Nonetheless, we are still able to check whether a given domain exist to reduce the number of invalid ones. PHP has a function checkdnsrr which does the work nicely.

1 function email_exist($email) {
2     list($userid, $domain) = split("@", $email);
3     if (checkdnsrr($domain, "MX")) { return true;} else { return false;}
4 }

Using the function above will help us to verify whether a particular domain exist to trick user that you have an email checker if they really intend to fake one. However, Windows doesn’t support such function yet. Hence, we will need to create such function just for Windows server.

1 if(!function_exists('checkdnsrr'))
2 function checkdnsrr($hostName, $recType = '')
3 {
4  if(!empty($hostName)) {
5    if( $recType == '' ) $recType = "MX";
6    exec("nslookup -type=$recType $hostName", $result);
7    // check each line to find the one that starts with the host
8    // name. If it exists then the function succeeded.
9    foreach ($result as $line) {
10      if(eregi("^$hostName",$line)) {
11        return true;
12      }
13    }
14    // otherwise there was no mail handler for the domain
15    return false;
16  }
17  return false;
18 }

Once you have cater for both Linux and Windows server, you may want to create a full flag function to check on email such as the one shown below:

1 function check_email($email)
2 {
3     $email_error = false;
4     $Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
5     if ($Email == "") { email_error = true; }
6     elseif (!eregi("^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+", $Email)) { email_error = true; }
7     else {
8     list($Email, $domain) = split("@", $Email, 2);
9         if (! checkdnsrr($domain, "MX")) { email_error = true; }
10         else {
11         $array = array($Email, $domain);
12         $Email = implode("@", $array);
13         }
14     }
15     if (email_error) { return false; } else{return true;}
16 }

Now we know why we need to verify our email after we sign up for any particular services online! Since we cannot check whether a particular email exist, we will force to send out verification email to our user before they are able to access our portal. However, if you are interested to check through PHP forcefully, you may want to visit webdigi. They create a mail class to verify an email through checking the port of mail SMTP 25 but like i said previously it really depend on how each mail server is being design. This might not work. But we can still force user to verify their email through a simple script shown below,

1 function check_email($email)
2 {
3     $email_error = false;
4     $Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
5     if ($Email == "") { email_error = true; }
6     elseif (!eregi("^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+", $Email)) { email_error = true; }
7     else {
8     list($Email, $domain) = split("@", $Email, 2);
9         if (! checkdnsrr($domain, "MX")) { email_error = true; }
10         else {
11         $array = array($Email, $domain);
12         $Email = implode("@", $array);
13         }
14     }
15     if (email_error) { return false; } else{return true;}
16 }
17 function EmailValidation($email) {
18     if (check_email($email)) {
19     $domain = explode( "@", $email );
20         if ( @fsockopen ($domain[1],80,$errno,$errstr,3)) {
21             $code = "here we place a secret key  with the email address: $email";
22             mail($email, "Your Verification Code", "Please click the following URL to verify your email:\n\n ". $_SERVER['PHP_SELF']."/?v=$code&email=$email","From: \"example\" <>");
23             echo "Your account needs to be verify. We have send you an email, click the link provided and you are verified.";
24             return true;
25         } else {
26             return false; //if a connection cannot be established return false
27         }
28     } else {
29         return false; //if email address is an invalid format return false
30     }
31 }
32 function EmailForm(){
33     if(empty($_POST['email'])){
34         echo "<form action=".$_SERVER['PHP_SELF']." method='post'>
35         <table border='0'>
36         <tr>
37         <td>Email</td>
38         <td><input name='email' type='text' id='email' /></td>
39         </tr>
40         <tr>
41         <td> </td>
42         <td><input type='submit' name='Submit' value='Validate' /></td>
43         </tr>
44         </table>
45         </form>";
46     } elseif(isset($_POST['email'])) {
47         if(EmailValidation($_POST['email'])) {
48             echo "An email has been sent to you. Please follow the instructions to activate your account.";
49         } else {
50             echo "Your email address appears to be invalid. Please try again.";
51         }
52     }else elseif(isset($_GET['v']) && isset($_GET['email'])) {
53         $clean['emai'] = $_GET['email']; //need to filter these data to be clean
54         $clean['v'] = $_GET['v']; //need to filter these data to be clean
55         $code = "here we place a secret key  with the email address: $email";
56         $code = md5($code);
57         if ($clean['v'] != $code) {
58             echo "The Verification Code is invalid. Please Try Again.";
59             exit(0);
60         }else
61         echo "The email ".$clean['emai']." has been verified";
62     }else {
63         echo "An error has occured, please contact the administrator.";
64     }
65 }
66 EmailForm();

Might be a bit confusing but i believe you will get the above code since its quite simple. Instead of breaking them into different pages, i sum them up on a single one.


The above solution can help many people to verify the content that the user has entered. Remember it is not safe to trust user input and such verification can come in handle. On the other hand, this can also help us to check broken and invalid links so that we get the information we need from our users. The information above might not be solid but it is good enough for me and hoping it will work for you.

Copy from:

By dbglory Posted in PHP

129 comments on “Use PHP To Check Whether Remote URL, Email Or Image Link Exist

  1. We’re a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable information to work on. You’ve done a formidable job and our
    entire community will be thankful to you.

  2. Magnificent goods from you, man. I have understand your stuff previous to and you
    are just too fantastic. I actually like what you have acquired here, really like what you are saying and the way in which you
    say it. You make it enjoyable and you still take care of to keep it sensible.
    I can’t wait to read far more from you. This is actually a wonderful website.

  3. Hello there, I believe your blog could be having browser
    compatibility issues. When I look at your blog in Safari, it looks fine however,
    if opening in Internet Explorer, it’s got some overlapping issues. I merely wanted to provide you with a quick heads up! Other than that, wonderful site!

  4. Hello great website! Does running a blog such
    as this take a large amount of work? I have no knowledge of programming however I was hoping
    to start my own blog soon. Anyway, should you have any
    suggestions or tips for new blog owners please share.

    I understand this is off topic however I just wanted to
    ask. Kudos!

    • That doesn’t take a large amount work. I’m a software enginner IT and I have already some knowledge of programing. These posts are my experience and good articles that I accumulated when I need to search on a problem.
      Try yourself, write articles and after a couple of month you have many knowledge and good website 🙂

  5. But how enjoy you know just what exactly are the
    optimum and hottest and furthermore most likely at be profitable Equities to invest
    to? Researching penny stocks is very new from researching the perfect traditional stock and / or it is likewise much more a
    challenge to do.

  6. That is really fascinating, You’re an overly professional blogger. I have joined your feed and look forward to seeking extra of your wonderful post. Additionally, I have shared your website in my social networks

  7. I’m not sure where you’re getting your information, but good topic.
    I needs to spend some time finding out more or working
    out more. Thanks for fantastic info I was looking for this information for my mission.

  8. In typical, confirmed search engine optimization procedures
    contain effective use of search motor optimization approaches.
    You will need to have some originality and relevance
    with your vital text but do seo ideal practice is to use related potent important phrases on your

  9. Usually I do not read article on blogs, but I wish to say that this
    write-up very forced me to take a look at and do it!
    Your writing taste has been amazed me. Thank you, quite great post.

  10. Hi there, i read your blog from time to time and i own a similar one and i
    was just curious if you get a lot of spam remarks? If so how do
    you stop it, any plugin or anything you can recommend?
    I get so much lately it’s driving me mad so any support is very much appreciated.

    • This blog bases on wordpress engine and hosting, I don’t host my own server. You don’t need to manage these spams, they are removed automatically

  11. Howdy would you mind sharing which blog platform you’re using? I’m going to start my own blog in the near future but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m
    looking for something unique. P.S Apologies
    for being off-topic but I had to ask!

  12. I am really impressed together with your writing skills and also with the format to your weblog.
    Is this a paid theme or did you modify it yourself? Either
    way stay up the excellent high quality writing, it is uncommon
    to look a nice blog like this one today..

  13. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is important and everything.

    But think of if you added some great photos or video clips to give your posts more, “pop”!
    Your content is excellent but with images and video clips,
    this site could definitely be one of the greatest in its niche.

    Very good blog!

    • Thank you for your comment. I concentrate too much on the content so I forgot somethings to attract the reader. I will improve, thank you one more times

  14. Hi there! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept chatting about this. I will forward this post to him. Pretty sure he will have a good read. Thank you for sharing!

  15. I was wondering if you ever thought of changing the
    layout of your blog? Its very well written; I love what
    youve got to say. But maybe you could a little more in the way of content so
    people could connect with it better. Youve got an awful lot
    of text for only having 1 or two pictures. Maybe you could space it out better?

  16. Hi there just wanted to give you a quick heads
    up and let you know a few of the images aren’t loading properly. I’m not sure
    why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.

  17. Hi, I do think this is an excellent blog. I stumbledupon it 😉 I will come back yet again since I book marked it.
    Money and freedom is the best way to change,
    may you be rich and continue to help others.

  18. This design is wicked! You obviously know how to keep
    a reader amused. Between your wit and your videos, I was almost moved to
    start my own blog (well, almost…HaHa!) Excellent job.
    I really enjoyed what you had to say, and more
    than that, how you presented it. Too cool!

  19. Its like you learn my mind! You appear to grasp
    so much about this, such as you wrote the ebook
    in it or something. I feel that you just can do with some
    percent to pressure the message house a bit, however instead of that, that is excellent blog.
    A fantastic read. I will definitely be back.

  20. Hmm is anyone else experiencing problems with the pictures on
    this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog.
    Any responses would be greatly appreciated.

  21. I think this is one of the most important info for me.
    And i’m glad reading your article. But want to remark on some general things, The web site style is wonderful, the articles is really great : D. Good job, cheers

  22. I do not even know how I stopped up right here, but I thought this publish was great.
    I don’t recognize who you’re however certainly you are going to a famous blogger
    should you aren’t already. Cheers!

  23. Excellent items from you, man. I’ve take into account your stuff prior to and you’re just extremely magnificent.
    I actually like what you’ve received right here, certainly like what you’re saying and the way in which
    by which you assert it. You’re making it entertaining and you still care for to stay it smart. I can not wait to learn much more from you. That is actually a terrific web site.

  24. When I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and from now
    on every time a comment is added I receive four emails with
    the exact same comment. There has to be an easy method you can remove
    me from that service? Thanks!

  25. I’m pretty pleased to uncover this great site. I want to to thank you for ones time for this particularly fantastic read!! I definitely enjoyed every part of it and i also have you book marked to see new things in your blog.

  26. Thanks for ones marvelous posting! I quite enjoyed reading it, you could be a great author.

    I will remember to bookmark your blog and definitely will come back very soon.
    I want to encourage yourself to continue your great
    job, have a nice weekend!

  27. I do consider all of the concepts you’ve presented in your post.
    They’re very convincing and will certainly work. Nonetheless,
    the posts are too quick for beginners. Could you please prolong them a little from subsequent time?

    Thank you for the post.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s