cURL not following the Location: header

2019-07-30 14:09发布

问题:

I'm trying to use Rapidshare's API to download a file. To do so, I need to request their download subroutine twice. Once to get the appropriate download server to use, and secondly to request the download again on the server that the first request gave me. The second call is what sends the file.

On the first call, it returns a header with a Location: blah field, and I need to follow this location. So I did this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=$file_id&filename=$file_name&try=1&login={$account['username']}&password={$account['password']}");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$resp = curl_exec($ch);
curl_close($ch);

Unfortunately, it doesn't seem to be following the location header, because nothing is being returned in $resp. If I put the URL in my browser, it successfully follows the location header and gives me the output of the API call, so it must be something wrong with PHP or cURL.

Can anyone hazard a guess on what it might be? I've been fiddling for 30 minutes minutes now and have no idea.

Thanks for any help!

回答1:

change the CURLOPT_HEADER to true.

curl_setopt($ch, CURLOPT_HEADER, 1);

If I've read the documentation right, that will return the requested page's heaader, with contains the "Location" Directive, and by having CURLOPT_FOLLOWLOCATION set to true it should follow that redirect, and any others via the Location directive.