Page 1 of 1

PHP copy()

Posted: Mon Feb 02, 2009 10:40 am
by dvation
I have a bit of code that downloads a remote file from another web server to the local web server. That part is easy:

Code: Select all

$srcRoot = "http://www.domain.com/thefile.pdf";
$desRoot = "../files/thefile.pdf";
copy($srcRoot,$desRoot);
This works fine, except when the source file is not available. The copy function, instead, downloads the 404 error page that comes up when trying to access a file that doesn't exist on the remote web server. How can I test to make sure the file is there before running the copy function?

I've tried is_file(), exists(), fopen(), is_readable(), file_exists() ... but they all lead to the same problem that there *is* readable content there, it's just a 404 page not the pdf I intended.

Re: PHP copy()

Posted: Mon Feb 02, 2009 10:52 am
by pickle
Can you somehow make a request & check the headers you get back?

What about downloading to a temporary location. If the downloaded file is the same size as the 404 page, you know you didn't get the proper file & you don't copy the downloaded file into the permanent location.

Re: PHP copy()

Posted: Mon Feb 02, 2009 10:54 am
by VladSun
You may use cURL
http://bg2.php.net/manual/en/function.curl-error.php

It's better to use it because file functions may not be able to access remote content - it depends on the security settings in php.ini.

Re: PHP copy()

Posted: Mon Feb 02, 2009 11:22 am
by dvation
The cURL method didn't quite work the way I expected but I've never used it before and may have had a logic error.

However you both gave me an idea...If I read the first 10 bytes of the file I can see if it's a PDF or the 404 page just by searching the string.
This was the result:

Code: Select all

if(strchr(file_get_contents($srcRoot, 0, NULL, -1, 10),"PDF")){ echo "its a pdf"; } else { echo "it's NOT a pdf"; }
And it works! Thank you :)