PHP5.0~5.6 compatibility of various versions cURL file upload function

不言
Release: 2023-03-29 06:50:01
Original
1430 people have browsed it

This article mainly introduces the cURL file upload function of the compatibility of various versions of PHP5.0~5.6, and analyzes the relevant implementation skills and precautions for the curl file upload operation of various common versions of PHP in the form of examples. Friends in need can refer to it. Next

The example of this article analyzes the compatibility of cURL file upload function of each version of PHP5.0~5.6. Share it with everyone for your reference, the details are as follows:

A recent requirement is to call cURL through PHP to upload files in the multipart/form-data format. A few pitfalls are enough for an article.

Important warning

Don’t read the official Chinese documentation of PHP! The version can’t keep up and it will kill you!

The difference between cURL between different versions of PHP

PHP’s cURL supports passing an associative array toCURL_POSTFIELDS(while not a string) to generate a POST request formultipart/form-data.

Traditionally, PHP's cURL supports attaching files by using the "@ file full path" syntax in the array data for cURL to read and upload. This is consistent with the syntax for directly calling the cURL program from the command line:

curl_setopt(ch, CURLOPT_POSTFIELDS, array( 'file' => '@'.realpath('image.png'), ));
Copy after login

equals

$ curl -F "file=@/absolute/path/to/image.png" 
Copy after login

But PHP has introduced a new CURLFile class since 5.5 to point to files. The CURLFile class can also define in detail additional information such as MIME types, file names, etc. that may appear in multipart/form-data data. PHP recommends using CURLFile instead of the old@syntax:

curl_setopt(ch, CURLOPT_POSTFIELDS, [ 'file' => new CURLFile(realpath('image.png')), ]);
Copy after login

PHP 5.5 also introduces theCURL_SAFE_UPLOADoption, which can Forces PHP's cURL module to reject the old@syntax and only accept CURLFile-style files. The default value is false for 5.5 and true for 5.6.

But the pitfall is: the@syntax has been deprecated in 5.5, and was directly deleted in 5.6 (it will generate ErorException: The usage of the@ filenameAPI for file uploading is deprecated. Please use the CURLFile class instead).

For PHP 5.6, manually settingCURL_SAFE_UPLOADto false is meaningless. It is not literally understood as "set to false to enable the old unsafe method" - the old method has completely ceased to exist as obsolete syntax.PHP 5.6 == CURLFile only, don't have any illusions.

My deployment environment is 5.4 (@Syntax only), but the development environment is 5.6 (CURLFileonly). Neither is focused on 5.5, a transitional version that both support. As a result, two sets of codes with environmental judgment must be written.

Now comes the problem...

Environmental judgment: Be careful of the magic number!

I have seen this kind of environment judgment code:

if (version_compare(phpversion(), '5.4.0') >= 0)
Copy after login

I have only one evaluation for this kind of code Word: Shit.

This judgment falls into the typical magic number trap. The version number appears inexplicably in the code. Without checking the PHP manual and update history for a long time, it is difficult to understand which function change the author is stuck on.

Code should return to its origins. Our actual needs are actually: use CURLFile first, without regressing to the traditional@syntax. Then the code comes:

if (class_exists('\CURLFile')) { $field = array('fieldname' => new \CURLFile(realpath($filepath))); } else { $field = array('fieldname' => '@' . realpath($filepath)); }
Copy after login

Recommended explicitly specified degradation options

From From a reliable perspective, it is recommended to specify the value ofCURL_SAFE_UPLOADto clearly tell PHP whether to tolerate or prohibit the old@syntax. Note that theCURLOPT_SAFE_UPLOADconstant itself may not exist in lower versions of PHP. You need to judge:

if (class_exists('\CURLFile')) { curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true); } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); } }
Copy after login

cURL option setting The order

Whether it iscurl_setopt()single orcurl_setopt_array()batch, the cURL options are always set one by one to take effect, and Setting options immediately affects cURL's behavior when setting subsequent options.

For example,CURLOPT_SAFE_UPLOADis related to the behavior ofCURLOPT_POSTFIELDS. IfCURLOPT_POSTFIELDSis set first and thenCURLOPT_SAFE_UPLOADis set, the latter constraint will not take effect. Because when setting the former, cURL has already completed the actual reading and processing of the data!

cURL has several options that have this pitfall, so be careful. Fortunately, there are not many options for this kind of "dependency", and the mechanism is not complicated, so it can be handled simply. My method is to set all the options in batches first, and then usecurl_setopt()single-shot settingCURLOPT_POSTFIELDSuntil just beforecurl_exec().

In fact, in the array used bycurl_setopt_array(), it is guaranteed that the position ofCURLOPT_POSTFIELDSis also reliable at the back. PHP's associative arrays are sequentially guaranteed. We can also assume that the internal execution order ofcurl_setopt_array()must be in order from beginning to end (well, I know that assume is not a good thing, but some are too simple. As a matter of fact, let me make the bare minimum assertion), so don’t worry.

My approach is just to add extra insurance to the code performance, highlighting the importance of order to prevent future cheating.

Namespace

PHP versions 5.2 or below do not have namespaces. If the space delimiter\is used in the code, a parser error will occur. It's actually easy to take care of PHP 5.2, just give up the namespace.

What should be noted is PHP 5.3 with namespace. Whether calling CURLFile or usingclass_exists()to determine the existence of CURLFile, it is recommended to write\CURLFileto clearly specify the top-level space to prevent the code from crashing when it is wrapped in the namespace.

Related recommendations:

Compatible with the cURL file upload function of php5 and php7

##

The above is the detailed content of PHP5.0~5.6 compatibility of various versions cURL file upload function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!