Để lưu file (ảnh, video) từ 1 url, trong php có rất nhiều cách làm, chúng tôi VinaSupport đã tổng hợp 4 cách sau:
- Hàm file_get_contents, file_put_contents
- Hàm copy
- Sử dụng fopen
- Sử dụng CURL
1. Hàm file_get_contents, file_put_contents
Sử dụng hàm file_get_contents để lấy nội dung của của url và file_put_contents để lưu lại nội dung thành file.
$url = 'https://vinasupport.com/assets/img/vinasupport_logo.png'; $saveUrl = '/tmp/vinasupport_logo.png'; file_put_contents($saveUrl, file_get_contents($url));
Tham khảo Doc của PHP ở đây.
- https://www.php.net/manual/en/function.file-get-contents.php
- https://www.php.net/manual/en/function.file-put-contents.php
Yêu cầu tham số allow_url_fopen trong php.ini phải set là true
2. Hàm copy
copy('https://vinasupport.com/assets/img/vinasupport_logo.png', '/tmp/vinasupport_logo.png');
Tham khảo Doc của hàm copy ở đây, nó cũng yêu cầu tham số allow_url_fopen trong php.ini phải set là true
- https://www.php.net/manual/en/function.copy.php
3. Sử dụng fopen
Một phương án khác là các bạn sử dụng hàm fopen, fread, fwrite để xử lý lưu file như bên dưới
$in = fopen('https://vinasupport.com/assets/img/vinasupport_logo.png', "rb");
$out = fopen('/tmp/vinasupport_logo.png', "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
4. Sử dụng CURL
Đây là phương án xử lý lưu file tốt nhất và hiệu quả nhất hiện này với rất nhiều tùy chọn.
set_time_limit(0);
$image = 'https://vinasupport.com/assets/img/vinasupport_logo.png';
// Save image name
$saveImageName = basename($image);
// Save Image Path
$saveImagePath = '/tmp/' . $saveImageName;
// This is the file where we save the information
$fp = fopen ($saveImagePath, 'w+');
// Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$image));
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);
Nguồn: vinasupport.com