Php uses curl to download a file of the specified size,
Php uses the libcurl-based curl function to initiate an http request to the target url and obtain the returned response content. The common request method is similar to the following code:
Public function callFunction ($ url, $ postData, $ method, header = '') {$ maxRetryTimes = 3; $ curl = curl_init (); /****** initialize the request parameter start ******/if (strtoupper ($ method )! = 'Get' & $ postData) {curl_setopt ($ curl, CURLOPT_POSTFIELDS, json_encode ($ postData);} elseif (strtoupper ($ method) === 'get' & $ postData) {$ url. = '? '. Http_build_query ($ postData);}/****** initialize the request parameter end ******/curl_setopt_array ($ curl, array (CURLOPT_URL => $ url, CURLOPT_TIMEOUT => 10, CURLOPT_NOBODY => 0, CURLOPT_RETURNTRANSFER => 1); if (method = 'post') {curl_setopt ($ curl, CURLOPT_POST, true );} if (false = empty () {curl_setopt ($ curl, CURLOPT_HTTPHEADER, $ header) ;}$ response = false; while ($ response = false) & (-- $ maxRetryTimes> 0) {$ response = trim (curl_exec ($ curl);} return $ response ;}
In the above Code, $ response is the data obtained from $ url in this http request initiated by curl. If the range parameter is not specified in $ header, regardless of the resource size, the request must be complete and the complete content of the URI should be returned. Generally, curl is used to request some interfaces or call a function remotely to obtain data. Therefore, the CURLOPT_TIMEOUT parameter is very important in this scenario.
For curl usage scenarios, you must not only access data interfaces, but also check for any url resources to provide the correct http service. When a user fills in a url as a resource file, such as a pdf or ppt, if the network condition is poor, use curl to request a large resource, it will inevitably time out or consume more network resources. The previous policy was to completely download (the curl will download and store it in the memory), check the content size after the request is complete, and pause the monitoring task when the target value is exceeded. In this way, after the occurrence of the incident, the customer finally raised a new requirement that the task cannot be stopped and only download files of the specified size and return the md5 value. The customer verifies the correctness.
Some attempts have been made to solve this problem. The record process is as follows.
1. Try CURLOPT_MAXFILESIZE.
Php and libcurl versions have version requirements and are completely pre-handled. When the target is found to be greater than the setting, an error exceeding the size limit is directly returned instead of the download target, which does not meet the requirements.
2. Use the callback function of the curl download process.
Refer to Region.
$ch = curl_init();
$options = array(CURLOPT_URL => 'http://www.php.net/',
CURLOPT_HEADER => false,
CURLOPT_HEADERFUNCTION => 'on_curl_header',
CURLOPT_WRITEFUNCTION => 'on_curl_write'
);
The final implementation snippet:
Function on_curl_write ($ ch, $ data) {$ pid = getmypid (); $ downloadSizeRecorder = DownloadSizeRecorder: getInstance ($ pid); $ bytes = strlen ($ data ); $ downloadSizeRecorder-> downloadData. = $ data; $ downloadSizeRecorder-> downloadedFileSize + = $ bytes; // error_log ('on_curl_write '. $ downloadSizeRecorder-> downloadedFileSize. ">{$ downloadSizeRecorder-> maxSize} \ n", 3, '/tmp/hyb. log'); // make sure that the downloaded content is slightly greater than the maximum limit if (( $ DownloadSizeRecorder-> downloadedFileSize-$ bytes)> $ downloadSizeRecorder-> maxSize) {return false;} return $ bytes; // If the returned result is incorrect, an error is returned, interrupted download "errno": 23, "errmsg": "Failed writing body (0! = 16384 )"}
DownloadSizeRecorder is a class in singleton mode. It records the size during curl download and returns md5 of the downloaded content.
Class DownloadSizeRecorder {const ERROR_FAILED_WRITING = 23; // Failed writing body public $ downloadedFileSize; public $ maxSize; public $ pid; public $ hasOverMaxSize; public $ fileFullName; public $ downloadData; private static $ selfInstanceList = array (); public static function getInstance ($ pid) {if (! Isset (self ::$ selfInstanceList [$ pid]) {self ::$ selfInstanceList [$ pid] = new self ($ pid);} return self :: $ selfInstanceList [$ pid];} private function _ construct ($ pid) {$ this-> pid = $ pid; $ this-> downloadedFileSize = 0; $ this-> fileFullName = ''; $ this-> hasOverMaxSize = false; $ this-> downloadData ='';}/*** save the file */public function saveMaxSizeData2File () {if (empty ($ resp_data) {$ resp_data = $ this-> dow NloadData;} $ fileFullName = '/tmp/http _'. $ this-> pid. '_'. time (). "_ {$ this-> maxSize }. download "; if ($ resp_data & strlen ($ resp_data)> 0) {list ($ headerOnly, $ bodyOnly) = explode (" \ r \ n ", $ resp_data, 2); $ saveDataLenth = ($ this-> downloadedFileSize <$ this-> maxSize )? $ This-> downloadedFileSize: $ this-> maxSize; $ needSaveData = substr ($ bodyOnly, 0, $ saveDataLenth); if (empty ($ needSaveData) {return ;} file_put_contents ($ fileFullName, $ needSaveData); if (file_exists ($ fileFullName) {$ this-> fileFullName = $ fileFullName ;}}} /*** return file md5 * @ return string */public function returnFileMd5 () {$ md5 = ''; if (file_exists ($ this-> fileFullName )) {$ md5 = md5_file ($ this-> fi LeFullName);} return $ md5;}/*** returns the downloaded size * @ return int */public function returnSize () {return ($ this-> downloadedFileSize <$ this-> maxSize )? $ This-> downloadedFileSize: $ this-> maxSize;}/*** Delete the downloaded file */public function deleteFile () {if (file_exists ($ this-> fileFullName )) {unlink ($ this-> fileFullName );}}}
Restrict the download size in the curl Request Code instance.
...... Curl_setopt ($ ch, CURLOPT_WRITEFUNCTION, 'on _ curl_write '); // sets the callback function ...... $ Pid = getmypid (); $ downloadSizeRecorder = DownloadSizeRecorder: getInstance ($ pid); $ downloadSizeRecorder-> maxSize = $ size_limit ;...... // Initiate a curl request $ response = curl_exec ($ ch );...... // Save the file and return md5 $ downloadSizeRecorder-> extract (); // save $ downloadFileMd5 = $ response-> returnFileMd5 (); $ downloadedfile_size = $ downloadSizeRecorder-> returnSize (); $ downloadSizeRecorder-> deleteFile ();
Here, I stepped on a trap. After on_curl_write is added, $ response returns true, causing an exception when retrieving the returned content. Fortunately, the download size has been limited in real time, and downloadData is used to record the downloaded content, which can be directly used.
if($response === true){
$response = $downloadSizeRecorder->downloadData;
}