PHP copy()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dvation
Forum Newbie
Posts: 2
Joined: Mon Feb 02, 2009 10:34 am

PHP copy()

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: PHP copy()

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: PHP copy()

Post 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.
There are 10 types of people in this world, those who understand binary and those who don't
dvation
Forum Newbie
Posts: 2
Joined: Mon Feb 02, 2009 10:34 am

Re: PHP copy()

Post 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 :)
Post Reply