Welcome Guest, Not a member yet? Register   Sign In
How to check if file exists via URL
#1

[eluser]codex[/eluser]
When you try to get a file that doesn't exist you get the 'failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found'-error, but how do you prevent this? I'm using file_exists to check if a file is present, but it chokes on the 404.

For instance
Code:
http://img.youtube.com/vi/XgdmsJsOKJc/2.jpg
is valid, while
Code:
http://img.youtube.com/vi/jksfhjhfjfdjsfjdsjhjhfd/2.jpg
isn't.

How do you check the validity??
#2

[eluser]Phil Sturgeon[/eluser]
file_exists() is a local-only function, cannot check remote servers. You can use fopen for that to see if it is able to open the file, then close it again.

There are plenty of functions for this around the net but most of them seem larger and slower than the simple fopen.
#3

[eluser]Pygon[/eluser]
Code:
if( fopen('$file','r') )
{
//exists
}

This would cover a simple version or whether you get a response on the URL.

The reason that many of these functions seem "heavy", I would assume, is because they attempt to determine whether the file is real or simply a custom 404 error page (most likely via socket >> request >> mime type comparison).
#4

[eluser]codex[/eluser]
[quote author="Pygon" date="1193857196"]
Code:
if( fopen('$file','r') )
{
//exists
}

This would cover a simple version or whether you get a response on the URL.

The reason that many of these functions seem "heavy", I would assume, is because they attempt to determine whether the file is real or simply a custom 404 error page (most likely via socket >> request >> mime type comparison).[/quote]

Well, I actually had tried this, but it doesn't validate the mimetype. It returns a true, but this is not what I'm looking for. I'm looking for 'are you a valid imagefile?'
#5

[eluser]Phil Sturgeon[/eluser]
You should have said that then! We were telling you how to do remote file_exists because thats what you asked for.

Some of the larger more detailed functions I was talking about here.
#6

[eluser]codex[/eluser]
[quote author="thepyromaniac" date="1193857889"]You should have said that then! We were telling you how to do remote file_exists because thats what you asked for.

Some of the larger more detailed functions I was talking about here.[/quote]

Sorry, I thought it was clear what I was after. Guess not ;-)

Thanks!
#7

[eluser]Pygon[/eluser]
[quote author="codex" date="1193858394"]
Sorry, I thought it was clear what I was after. Guess not ;-)
[quote]

Yah -- Definately was no mention of "valid IMAGE file via URL" -- just "file_exists" which doesn't care.

I would suggest looking for a pre-built class.
#8

[eluser]Unknown[/eluser]
fopen throughs error when file does not exist.




Theme © iAndrew 2016 - Forum software by © MyBB