php5.0~5.6 version Compatibility Curl File Upload Function example analysis PHP tips

Source: Internet
Author: User
Tags curl options
This article mainly introduces the php5.0~5.6 version of the compatibility Curl file upload function, combined with instance form analysis of PHP each common version of the Curl file upload operation related implementation tips and considerations, the need for friends can refer to the next

This paper analyzes the php5.0~5.6 version compatibility Curl file Upload function. Share to everyone for your reference, as follows:

A recent need to call curl via PHP to upload files in multipart/form-data format. Step on the pit a few, enough an article.

Important warning

Don't read PHP's official Chinese documentation! Version can't keep up with the pit dead you!

Different versions of PHP between curl differences

PHP's Curl supports CURL_POSTFIELDS post requests that are generated by passing associative arrays (rather than strings) multipart/form-data .

Traditionally, PHP's curl supports the use of the "@+ file full path" syntax in the array data to append files for curl to read and upload. This is consistent with the syntax of the command line calling the Curl program directly:

curl_setopt (CH, curlopt_postfields, Array (  ' file ' = ' @ '. Realpath (' Image.png '),));

equals

$ curl-f "File=@/absolute/path/to/image.png" <url>

But PHP introduced a new Curlfile class from 5.5 to point to the file. The Curlfile class can also define in detail the additional information that may appear in the Multipart/form-data data, such as MIME type, file name, and so on. PHP recommends using Curlfile instead of the old @ syntax:

curl_setopt (CH, curlopt_postfields, [  ' file ' = = new Curlfile (Realpath (' image.png ')),]);

PHP 5.5 also introduces the CURL_SAFE_UPLOAD option to force PHP's Curl module to reject the old @ syntax and accept only curlfile files. The default value of 5.5 for the default value of false,5.6 is true.

But the point of the pit is that the @ syntax has been deprecated in 5.5 and has been removed directly in 5.6 (erorexception:the usage of the API for file uploading will be generated) is @filename Depr Ecated. Use the Curlfile class instead).

For PHP 5.6+, it is meaningless to set the manual CURL_SAFE_UPLOAD to False. There is no literal sense of "set to False, you can open the old unsafe way"--the old way has been completely absent as an obsolete grammar. PHP 5.6+ = = Curlfileonly, do not have any illusions.

My deployment environment is 5.4 ( @ syntax only ), but the development environment is 5.6 ( curlfile only). It's not even on the 5.5. Both support the transition version, and the result is that two sets of code with environmental judgments must be written.

Now the question is coming ...

Environmental judgment: Beware of magic numbers!

I've seen this code for environmental judgments:

if (Version_compare (Phpversion (), ' 5.4.0 ') >= 0)

My comment on this code is only one word: excrement.

This judgment falls into a typical magic number trap. The version number is inexplicably in the code, not a half-day PHP manual and update history, it is difficult to understand the author is stuck in which function changes.

The code should return to its source. Our actual demand is actually: there are curlfile priority to use, no longer degenerate to the traditional @ grammar. So the code is here:

if (class_exists (' \curlfile ')) {  $field = array (' fieldname ' = = new \curlfile (Realpath ($filepath)));} else {  $field = Array (' fieldname ' = ' @ '. Realpath ($filepath));}

Recommended for explicitly specified degradation options

From a reliable point of view, it CURL_SAFE_UPLOAD is recommended to explicitly tell PHP whether to tolerate or disallow the old @ syntax. Note that in the low version of PHP the CURLOPT_SAFE_UPLOAD constants themselves may not exist and need to be judged:

if (class_exists (' \curlfile ')) {  curl_setopt ($ch, Curlopt_safe_upload, True);} else {  if (defined (' Curlopt_ Safe_upload ') {    curl_setopt ($ch, Curlopt_safe_upload, false);  }}

The order in which the curl options are set

Regardless of whether the single-release curl_setopt() is curl_setopt_array() batch, the Curl option is always set to take effect one, and the SET option immediately affects the behavior of curl when setting subsequent options.

For example, CURLOPT_SAFE_UPLOAD it is CURLOPT_POSTFIELDS related to the behavior. If you set the reset first CURLOPT_POSTFIELDS CURLOPT_SAFE_UPLOAD , the latter's constraint will not take effect. Since the former is set, Curl has already finished reading the actual data!

Curl has a few options for this pit, so be careful. Fortunately, the existence of "dependency" of the options are not many, the mechanism is not complex, simple processing can be. My approach is to set all the options in bulk, and then curl_exec() use the single-shot setting until the first moment curl_setopt() CURLOPT_POSTFIELDS .

In fact in curl_setopt_array() the array used, the guaranteed CURLOPT_POSTFIELDS position is also reliable behind. PHP's associative arrays are guaranteed in sequence, and we can assume that curl_setopt_array() the internal execution order must be sequential (well I know that assume is not a good thing, but some of the facts are too superficial to allow me to make the next minimum assertion), so be assured.

My approach is simply to add an excess of insurance to the code performance, highlighting the importance of order to prevent your hands from becoming cheap.

Name space

PHP 5.2 or below does not have a namespace. The space delimiter in the code \ throws a parser error. To take care of PHP 5.2 is actually easy to think about, give up the namespace.

It is the PHP 5.3+ that has the namespace. Whether calling Curlfile or class_exists() judging the existence of curlfile, it is recommended to write \CURLFile explicitly designated top-level space to prevent the code from collapsing when it is wrapped within a namespace.

Articles you may be interested in:

Compatible PHP5 and PHP7 analysis of the query implementation method for PHP block with curl text

PHP Tips upload Function Example analysis PHP tips

PHP binary Search Algorithm example analysis PHP tips

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.