Technical skills, technology news, analysis ….

Main menu

Post navigation

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,

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

functioncheckRemoteFile($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

returntrue;

12

}

13

else

14

{

15

returnfalse;

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

functionurl_exists($url) {

2

if(@file_get_contents($url,0,NULL,0,1))

3

{return1;}

4

else

5

{ return0;}

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

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 ‘http://example.com?p=231′, 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:

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.

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

functionimage_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

functionemail_exist($email) {

2

list($userid, $domain) = split("@", $email);

3

if(checkdnsrr($domain, "MX")) { returntrue;} else{ returnfalse;}

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

functioncheckdnsrr($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($resultas$line) {

10

if(eregi("^$hostName",$line)) {

11

returntrue;

12

}

13

}

14

// otherwise there was no mail handler for the domain

15

returnfalse;

16

}

17

returnfalse;

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:

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,

echo"Your account needs to be verify. We have send you an email, click the link provided and you are verified.";

24

returntrue;

25

} else{

26

returnfalse; //if a connection cannot be established return false

27

}

28

} else{

29

returnfalse; //if email address is an invalid format return false

30

}

31

}

32

functionEmailForm(){

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

}elseelseif(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.

Summary

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.

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.

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.

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!

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.

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 🙂

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.

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

It has now been just more than a year considering that purchasing this product and I am nonetheless
completely in enjoy with it! This product is nevertheless a dream come true!
I would get this more than once more! It performs completely.

I do believe all the ideas you have offered for your post.
They’re very convincing and will definitely work. Nonetheless, the posts are very quick for beginners. May you please lengthen them a bit from subsequent time? Thanks for the post.

I’m really enjoying the design and layout of your site. It’s a very easy
on the eyes which makes it much more enjoyable for me to come here and visit more often.
Did you hire out a developer to create your theme?
Superb work!

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.

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
site.

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.

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!

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..

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.

Wow! I’m really enjoying the layout of your web site. Are you using a custom made template or is this freely available to all individuals? If you really don’t want to say the name of it out in the general public, please be
sure to email me at: clifford_lorenz@yahoo.com.
I’d love to get my hands on this template! Bless you.

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!

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?

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.

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.

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!

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.

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

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!

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.

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!

Incredible! I’m genuinely enjoying the style and design of your web site. Are you using a customized template or is this readily available to all users? If you do not want to say the name of it out in the public, please email me at: carlota.bratton@gmail.com. I’d really enjoy to get my hands
on this theme! Cheers.

Hey there! Someone in my Facebook group shared this site with us
so I came to look it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my
followers! Wonderful blog and terrific design.

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.

Attractive component to content. I just stumbled upon your site and
in accession capital to assert that I get actually enjoyed account your blog posts.
Anyway I’ll be subscribing to your augment or even I achievement you access consistently rapidly.

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?