How to download and save a file to local path using CURL
Ok, got the solution. Sharing my answer.
$getFile = 'http://url to file/file.csv';
$getParams = array ();
$path = '/var/save/to/local/path/file_name.csv';
$fp = fopen($path, 'w');
$ch = curl_init($getFile);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies');
$data = curl_exec($ch);
if(fwrite($fp,$data))
{
return true;
}
else
{
return false;
}
Thanks all for your help.
Reference :
http://www.technologyworkshops.net/php/how-to-download-and-save-a-file-to-local-path-using-curl-t132.html
Save image from url with curl PHP
try this:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
and ensure that in php.ini allow_url_fopen is enable
Using cURL to save external files to my Server
$local_file = "/tmp/filename.flv";//This is the file where we save the information
$remote_file = "http://www.test.com/filename.flv"; //Here is the file we are downloading
$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
I've decided to update this answer almost 7 years later.
For those who have copy()
enabled for remote hosts, you can simply use:
copy("http://www.test.com/filename.flv", "/some/local/path/filename.flv");
Downloading Files with PHP and CURL
with the CURLOPT_RETURNTRANSFER
option is set curl_exec
will return downloaded content in the result. So, your variable $result
actually contains the content of the file (PKr�
... is a ZIP-header)
So, all you need, just to save the content of the variable in a file, instead of echo
ing it into the browser.
For example.
...
$result = curl_exec($ch);
file_put_contents('downloaded.zip', $result); // save the string to a file
curl_close ($ch);
php curl to download files
If i interpret this correct you want to build something like a cache where you download file x once from a remote server and after that the file should be served from your own server ?
If that is the case this could be a good approach for the problem:
class Downloader
{
private $path;
public $filename;
public function __construct()
{
$this->path = dirname(__FILE__);
}
public function getFile($url)
{
$fileName = $this->getFileName($url);
if(!file_exists($this->path."/".$fileName)){
$this->downloadFile($url,$fileName);
}
return file_get_contents($this->path."/".$fileName);
}
public function getFileName($url)
{
$slugs = explode("/", $url);
$this->filename = $slugs[count($slugs)-1];
return $this->filename;
}
private function downloadFile($url,$fileName)
{
//This is the file where we save the information
$fp = fopen ($this->path.'/'.$fileName, 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
}
}
$downloader = new Downloader();
$content = $downloader->getFile("YOUR URL");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$downloader->filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . mb_strlen($content));
print $content;
exit;
This is a very basic concept there are many point this have to be improved and customized for your use case.
Downloading a large file using curl
<?php
set_time_limit(0);
//This is the file where we save the information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
// make sure to set timeout to a high enough value
// if this is too low the download will be interrupted
curl_setopt($ch, CURLOPT_TIMEOUT, 600);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
php curl not saving file to location
OK, finally got it all working and here is the code if anyone else ever tries to do the same sort of thing!
I was missing these parts:
$dir = $_SERVER['DOCUMENT_ROOT'] . "/img/products/";
and
fwrite($file,$contents);
So here is my final code... credit to Sébastien for pointing me in the right direction. Thanks.
if($method == 'save')
{
$productId = Input::get('pId');
$removeProductImages = DB::table('product_ref_images')->where('product_id', '=', $productId)->delete();
$imagesData = Input::get('imageRefs');
$dir = $_SERVER['DOCUMENT_ROOT'] . "/img/products/";
$sortOrder = 0;
for ($i=0; $i < count($imagesData); $i++) {
$imgSrc = trim($imagesData[$i]['imgSrc']);
$imgId = trim($imagesData[$i]['imgId']);
$file = fopen($dir . basename($imgSrc), "wb");
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$ch = curl_init($imgSrc);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
$contents = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0)
{
Log::write("CURL", "cURL Error (".$curl_errno."): ".$curl_error);
break;
}
else
{
fwrite($file,$contents);
fclose($file);
$imageIds = DB::table('product_ref_images')->order_by('image_id', 'desc')->first();
if($imageIds == null)
{
$imageIds = 0;
}
else
{
$imageIds = $imageIds->image_id;
}
$updateImages = DB::table('product_ref_images')
->insert(array(
'image_id' => $imageIds + 1,
'product_id' => $productId,
'flickr_image_id' => $imgId,
'sort_order' => $sortOrder++,
'local_storage_url' => $dir . basename($imgSrc),
'created_at' => date("Y-m-d H:i:s"),
'updated_at' => date("Y-m-d H:i:s")
));
}
}
return Response::json('Complete');
}
Related Topics
I Want a Pagination to My Options Page of Wordpress Plugin
Codeigniter Redirect -- the Uri You Submitted Has Disallowed Characters
Jquery UI Saving Sortable List
How to Select MySQL Query with Foreign Language
PHP Array, Are Array Indexes Case Sensitive
Maximum Length of Generated Hash When Using Password_Hash
Echo PHP Variable from JavaScript
HTML Purifier: Removing an Element Conditionally Based on Its Attributes
Regular Expressions: How to Express \W Without Underscore
Laravel 5.3 - How to Add Sessions to 'Api' Without Csrf
How to Replace Multiple Values in PHP
How to Insert Multiple Rows in PHP Pdo MySQL