Monday 24 September 2018

Download a file using curl in PHP

Here is a quick curl snippet for php, that can download a remote file and save it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
 
set_time_limit(0);
 
//File to save the contents to
$fp = fopen ('files2.tar', '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);
 
//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 
$data = curl_exec($ch);//get curl response
 
//done
curl_close($ch);
The CURLOPT_FILE option takes a file resources and writes the content of the url to that file resource/handle. Also set the script time limit to something large so that the script does not end when downloading large files.

0 comments:

Post a Comment