- Downloading files with cURL in PHP
- Скачивание файлов с сайтов при помощи PHP и CURL
- Download Files With CURL PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP CURL FILE DOWNLOAD
- EXAMPLE 1) USING CURL TO DOWNLOAD FILES
- EXAMPLE 2) DOWNLOADING LARGE FILES
- EXAMPLE 3) SUPER SIMPLE DOWNLOAD
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- File Download With CURL in PHP
- Use the cURL to Download a File From a Given URL in PHP
- Related Article — PHP Download
Downloading files with cURL in PHP
This is a simple tutorial on how to download files with cURL in PHP.
Firstly, allow me to present you with the code (because let’s be honest, that’s what most of you came here for). The example below will download a fictional logo image via cURL. Simply change the $fileUrl and $saveTo variables to meet your requirements.
//Create a cURL handle. $ch = curl_init($fileUrl); //Pass our file handle to cURL. curl_setopt($ch, CURLOPT_FILE, $fp); //Timeout if the file doesn’t download after 20 seconds. curl_setopt($ch, CURLOPT_TIMEOUT, 20); //Execute the request. curl_exec($ch); //If there was an error, throw an Exception if(curl_errno($ch)) < throw new Exception(curl_error($ch)); >//Get the HTTP status code. $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //Close the cURL handler. curl_close($ch); //Close the file handler. fclose($fp); if($statusCode == 200) < echo 'Downloaded!'; >else
To download a file via cURL, we need to give it a file pointer resource. We can achieve this by using the fopen function like so:
//Create file pointer $fp = fopen($saveTo, 'w+');
On success, the fopen function will return a file pointer resource. Note that we pass in “w+” as the second parameter because “w+” tells PHP that we want to open the file for reading and writing.
After we’ve successfully set up our file pointer, we can hand it over to cURL via the CURLOPT_FILE option, like so:
//Pass our file handle to cURL. curl_setopt($ch, CURLOPT_FILE, $fp);
This tells cURL that we want to save the transferred data of our request to the given file. Note that we also set the option CURLOPT_TIMEOUT to 20 seconds, simply because larger file sizes may result in longer request (when it comes to downloading files, we need to be weary of the possibility of timeouts):
//Timeout after 20 seconds curl_setopt($ch, CURLOPT_TIMEOUT, 20);
As you can see, downloading a resource with cURL in PHP is not much different than sending a regular HTTP request. The only difference is that you need to give cURL a valid stream resource.
Скачивание файлов с сайтов при помощи PHP и CURL
CURL является отличным инструментом, для подключения к удаленным сайтам, что упрощает возможность отправки форм, загрузку целых страниц, или, как в нашем случае, загрузку файлов. В этом сниппете я покажу вам, как вы можете скачать файл прямо на диск с помощью CURL.
Примечание: чтобы упростить пример, в этой статье мы не будем выполнять проверку CURL запросов на ошибки. Вы же всегда должны делать это, функция curl_getinfo() главное подспорье в этом деле.
Вы можете прочитать ответ и записать его на диск, как показано в следующем листинге. $path место на сервере, где вы хотите, чтобы записать файл.
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true);
file_put_contents ( $path , $data );
Существует, однако, проблема с этим кодом. В данном примере, файл пишеться на диск не напрямую, а сперва целиком загружается в оперативную память. Я думаю здесь понятно, что можно запросто умереться в предел памяти для исполнения скрипта и схлопотать fatal error. Так что данный способ годиться если вы скачиваете маленькие файлы, мегабайт до 20-30.
Примечание: Даже если ваш лимит памяти установлен очень высоко, грузить сервер лишний раз тоже не хорошо.
В таком случае опять возложим всю черную работу на CURL и заставим его писать данные прямо в файловый поток. Сделать это можно с помощью директивы CURLOPT_FILE.
Для этого вы должны сначала создать новый указатель файла с помощью fореn(). Далее мы передаем этот указатель на файл для выполнения запроса. Наконец, мы закрываем файл.
curl_setopt( $ch , CURLOPT_FILE, $fp );
Вот и все, что нужно сделать, теперь можно не бояться о превышение лимита памяти для исполнения скрипта.
Download Files With CURL PHP (Simple Examples)
Welcome to a tutorial on how to download files with PHP CURL. Need to fetch a file from another server with PHP CURL? Yes, it is possible.
- $fh = fopen(«FILE», «w»);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, «HTTP://SITE.COM/FILE»);
- curl_setopt($ch, CURLOPT_FILE, $fh);
- curl_exec($ch);
- curl_close($ch);
That should cover the basics, but let us walk through a few more examples in this guide – Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP CURL FILE DOWNLOAD
All right, let us now get into the examples of downloading files with PHP CURL.
EXAMPLE 1) USING CURL TO DOWNLOAD FILES
else < $status = curl_getinfo($ch); // print_r($status); echo $status["http_code"] == 200 ? "OK" : "ERROR - " . $status["http_code"] ; >// (C3) CLOSE CURL & FILE curl_close($ch); fclose($fh);
- A bunch of settings, where to download the file from, where to save it to.
- Creating an “empty file” on the local server.
- Use CURL to download and save the specified source.
EXAMPLE 2) DOWNLOADING LARGE FILES
flush(); > // (D) DONE! echo "DONE."; fclose($sh); fclose($dh);
If you are dealing with very large files, I will recommend dropping CURL and just use fopen() fwrite() fread() instead – We can limit the number of bytes fread() can read at once, to prevent an “out-of-memory” error.
EXAMPLE 3) SUPER SIMPLE DOWNLOAD
For you guys who just want a really simple file download… We don’t actually even need CURL. Just file_put_contents() and file_get_contents() .
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
File Download With CURL in PHP
The -output or -o command is used to download files with cURL in PHP.
We can download a file with cURL by giving the URL to the file. cURL library is used for many purposes in PHP.
Use the cURL to Download a File From a Given URL in PHP
First of all, make sure cURL is enabled in your PHP. You can check it by running phpinfo() and enabling it from the php.ini file.
We are trying to download the files from the local server to the local server itself.
php // File download information set_time_limit(0); // if the file is large set the timeout. $to_download = "http://localhost/delftstack.jpg"; // the target url from which the file will be downloaded $downloaded = "newDelftstack.jpg"; // downloaded file url // File Handling $new_file = fopen($downloaded, "w") or die("cannot open" . $downloaded); // Setting the curl operations $cd = curl_init(); curl_setopt($cd, CURLOPT_URL, $to_download); curl_setopt($cd, CURLOPT_FILE, $new_file); curl_setopt($cd, CURLOPT_TIMEOUT, 30); // timeout is 30 seconds, to download the large files you may need to increase the timeout limit. // Running curl to download file curl_exec($cd); if (curl_errno($cd)) echo "the cURL error is : " . curl_error($cd); > else $status = curl_getinfo($cd); echo $status["http_code"] == 200 ? "The File is Downloaded" : "The error code is : " . $status["http_code"] ; // the http status 200 means everything is going well. the error codes can be 401, 403 or 404. > // close and finalize the operations. curl_close($cd); fclose($new_file); ?>
The output shows that the code can download a file from a given URL. To download the large files, we can increase the timeout limit.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.