PHP- Check If File Exists On Different Domain

Image frame
PHP- Check If File Exists On Different Domain
Maruf
Nov 20th, 2008
Maruf scribbled this post.

Earlier today I needed to find out if a file exists on a different domain. Initially I used the file_exists function, but then when that threw back an error I remembered that file_exists only checks whether a file or directory exists on the same server as the script.

After I played around with various functions, I came up with a few lines of code that actually works:

How to check if file exists on a different domain

1
2
3
4
5
6
7
8
9
10
11
12
<?
$image = "http://www.example.co.uk/images/1.jpg";
$handle = @fopen("$image", "r");
if(strpos($handle, "Resource id") !== false)
{
echo "file does exist";
}
else
{
echo "file does not exist";
}
?>

The logic explained

Ok, so if the file exists (1.jpg) the fopen function will throw back a “resource id” response. So I check the response to see if “response id” exists with the strpos function. It’s really as simple as that.

I’m not entirely sure if my method is the best, nor the most efficient, but it seems to work pretty well, and I can’t think of any other methods. Anyone know of any other/better methods?

Filed away: PHP

comments

Image frame
1

Nice. Cheers!

Ian
Mar 14th, 2009

feel free to leave a scribble

Name:
Email:
gravatar
What an image next to your comments?
visit gravatar.com
Message:
want a website, do ya?

latest projects

Image frame
Taylor El-Hage Photography
view site- Taylor El-Hage Photography
Image frame
Property Investment Project
view site- Property Investment Project

latest scribbles

latest comments

Kujie Gravatar frame
Kujie said
hi..thnks for ur great themes, i like to edit ”...
Evona Niewiadomska Gravatar frame
Evona Niewiadomska said
Hi I actually have the same question as...
Kerem Gravatar frame
Kerem said
Thanks from Turkey…

blog categories

Get a free quote