Skip to content

Instantly share code, notes, and snippets.

@jli168
Last active June 22, 2019 09:03
Show Gist options
  • Save jli168/90aeaa771bb748a766e5 to your computer and use it in GitHub Desktop.
Save jli168/90aeaa771bb748a766e5 to your computer and use it in GitHub Desktop.
download file to client using cURL
<?php
$ch = curl_init($url);
$fp = @fopen("../Files/System/TEST/temp.xml", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$file = "../Files/System/TEST/temp.xml";
$fp = fopen($file, "r");
?>
<?php
//http://stackoverflow.com/a/14149927
$file = 'https://googledrive.com/host/0B_3oJnpnNoF9UjlkVUwtWE5CY0U/city.jpg';
download($file);
function download($url) {
set_time_limit(0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$r = curl_exec($ch);
curl_close($ch);
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="' . basename($url) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($r)); // provide file size
header('Connection: close');
echo $r;
}
?>
<?php
set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);
?>
<?
//http://stackoverflow.com/a/13958587
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
//curl_setopt($ch, CURLOPT_BUFFERSIZE,128);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false); // needed to make progress function work
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);
function progress($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
if($download_size > 0)
echo $downloaded / $download_size * 100;
ob_flush();
flush();
sleep(1); // just to see effect
}
echo "Done";
ob_flush();
flush();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment