Search code examples
phpcurlgoogle-docs-api

cURL download file issues


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);

Solution

  • 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($ch, 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

    to know About Curl read this blog