
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to download large files through PHP script?
To download large files through PHP script, the code is as follows −
Example
<?php function readfile_chunked($filename,$retbytes=true) { $chunksize = 1*(1024*1024); // how many bytes per chunk the user wishes to read $buffer = ''; $cnt =0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, $chunksize); echo $buffer; if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes && $status) { return $cnt; // return number of bytes delivered like readfile() does. } return $status; } ?>
Output
This will produce the following output −
The large file will be downloaded.
The function ‘readfile_chunked’ (user defined) takes in two parameters- the name of the file and the default value of ‘true’ for the number of bytes returned meaning that large files have been successfully downloaded. The variable ‘chunksize’ has been declared with the number of bytes per chunk that needs to be read. The ‘buffer’ variable is assigned to null and the ‘cnt’ is set to 0. The file is opened in binary read mode and assigned the variable ‘handle’ .
Until the end of file of the ‘handle’ is reached, the while loop runs and reads the contents of the file based on the number of chunks that need to be read. Next it is displayed on the screen. If the value of ‘retbytes’ (the second parameter to the function) is true, the length of the buffer is added to the ‘cnt’ variable. Otherwise, the file is closed and the ‘cnt’ value is returned. In the end, the function returns the ‘status’.
- Related Questions & Answers
- How to upload large files above 500MB in PHP?
- Download file through an AJAX call in PHP
- How to stream large .mp4 files in HTML5?
- How to Handle Large CSV files with Pandas?
- How to download all pdf files with selenium python?
- How we can compress large Python files?
- How to force file download with PHP?
- Sending large files over internet
- How to scrape through Media Files in Python?
- How to download APK files from Google Play Store on Linux
- How to use chrome webdriver in Selenium to download files in Python?
- How to split or break large files into pieces in Linux?
- How to Download and Extract Tar Files with One Command in Linux
- Splitting and uploading extremely large files to Amazon S3
- How to sort a large number of csv files in ascending order in R?