tags:

views:

40

answers:

3

This is the sort of link I want to download with:

http://username:[email protected]/dl/file.zip

Edit: stackoverflow seems to go weird with colons, its username-colon-password.

Now, if I log out of the website and use the URL pattern above, it successfully authenticates and I can successfully download the file.

I have this cURL script:

<?php
echo "Attempting to download...<br />";
$out = fopen("zip.zip", 'wb');
if ($out == FALSE){
 die('File could not be opened, exiting.');
}

$ch = curl_init();

curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);

curl_exec($ch);   
curl_close($ch);
fclose($out);
?>

And for some reason, it just downloads a 0KB file. I'm pretty sure the coding is correct, but then it can't be if it's not working.

Any help? Thanks.

A: 

Have you tried the URL using curl in a shell?

brianegge
Hi, I don't have root access to my hosting account therefore I can't run any shell commands. But the host allows connections to port 80 so I don't think that's the problem.
Andy
Are you able to connect to other http resources using libcurl? Some web hosts block out going connections.
brianegge
+1  A: 

Try adding follow locations option:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

EDIT: Explanation In my experience, a lot of download links are redirected to another link that actually contains the file. Curl by default doesn't follow redirections, and requires the option to be enabled first.

To debug the problem, you can set the CURLOPT_RETURNTRANSFER option, and then print the curl_exec results:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
print_r($result);

If the header contains Location: ... parameter, then this is your problem.

notnoop
I get this error: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set - which I'm thinking might be my problem?
Andy
@Andy, look at updated answer
notnoop
See this post for a safe_mode redirection workaround: http://www.edmondscommerce.co.uk/blog/curl/php-curl-curlopt_followlocation-and-open_basedir-or-safe-mode/Alternatively, run curl locally from the command line (under Cygwin for windows), and see if you can post your data to the find destination. Running `curl -v` will show all the redirects which occur.
brianegge
A: 

curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);

novalis
Also not working, after looking around a but more, I think it needs cookies aswell to authenticate... as I have a username and password cookie in my browser. I'll try and get cURL to accept the cookie.
Andy