问题
I am trying to download a file from Google drive, but when I play the script, it gives me following error:
Moved Temporarily
The document has moved here.
My code is given below:
$source = "https://docs.google.com/uc?id=0B8tmy5YxFFGhM0szSUZWVl9qQWc&export=download";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
echo $data = curl_exec($ch);
echo $error = curl_error($ch);
//print_r($ch);
$destination = "data.csv";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
curl_close ($ch);
回答1:
function gett($url) {
$url = str_replace(" ", '%20', $url);
fopen("cookies.txt", "w");
$parts = parse_url($url);
$host = $parts['host'];
$ch = curl_init($url);
$header = Array('Connection:keep-alive',
'Proxy-Connection: Close',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1017.2 Safari/535.19',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.8',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Connection: Close');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, $_REQUEST['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
use this function .it will work
回答2:
Add this to you curl
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , true);
SO your cule code would be
$source = "https://docs.google.com/uc?id=0B8tmy5YxFFGhM0szSUZWVl9qQWc&export=download";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , true);
echo $data = curl_exec($ch);
echo $error = curl_error($ch);
That's means
This means that libcurl will re-send the same request on the new location and follow new Location:
回答3:
Looks like you're receiving a redirect. You can ask curl to follow redirects with the following:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
回答4:
Add this to your script, and you should be fine.
Currently, your script just looks in the url that you are specifying, and doesnt follow the redirections. So add this, and then your script will try the url you specify in the url field, and then goes through all the redirects and returns the final data, file, or whatever that is.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
来源:https://stackoverflow.com/questions/30437335/curl-download-file-issues