We help IT Professionals succeed at work.

How do I efficiently check if a remote file exists?

dead1ne
dead1ne asked
on
2,112 Views
Last Modified: 2008-05-21
I need an efficient way to check if a remote file exists. I was using the code below, however, it seemed to be horribly inefficient. I'm on a shared host and I had my account temporarily suspended due to excessive resource usage. I'm not sure what the problem with the method I was using is but I think it may be that the remote files that I'm checking are fairly large(200MB-1GB). My site gets around 70k hits a day so if it isn't possible to handle that on a shared host I'll just have to do without. Any help is greatly appreciated.
<?php
function checklink($link)
{
	if(!($handle=@fopen($link,'r')))
	{
		fclose($handle);
		return 0;
	}
	fclose($handle);
	return 1;
}
?>

Open in new window

Comment
Watch Question

There is a function for this, file_exists:
http://se2.php.net/function.file-exists

Regards,
Andreas

Author

Commented:
Sorry I should have mentioned that I tried that. It doesn't seem to work with URLs on my host.
The same URLs work with fopen, but not file_exists?
Did you try "opening" local files to see if tehre is any difference?

Regards,
Andreas
Maybe far fatched, but also check your PHP version. Just read about some problems in 5.2.
http://bugs.php.net/bug.php?id=40231

Regards,
Andreas

Author

Commented:
The php version on the server is 5.2.5. It works fine with local files but every remote file I try results in a false.
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Comment by mentioned "colleague":

I suggest replacing the "GET" in the solution with "HEAD". HEAD does the same thing as GET, but tells the server you're only interested in the headers of the file, not the actual contents.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.