Home  >  Article  >  Backend Development  >  PHP5.0~5.6 compatibility of various versions cURL file upload function

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

不言
不言Original
2018-06-01 11:51:221320browse

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 to CURL_POSTFIELDS(while not a string) to generate a POST request for multipart/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'),
));

equals

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

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')),
]);

PHP 5.5 also introduces the CURL_SAFE_UPLOAD option, 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 @ filename API for file uploading is deprecated. Please use the CURLFile class instead).

For PHP 5.6, manually setting CURL_SAFE_UPLOAD to 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 (CURLFile only). 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)

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));
}

Recommended explicitly specified degradation options

From From a reliable perspective, it is recommended to specify the value of CURL_SAFE_UPLOAD to clearly tell PHP whether to tolerate or prohibit the old @ syntax. Note that the CURLOPT_SAFE_UPLOAD constant 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);
  }
}

cURL option setting The order

Whether it is curl_setopt()single or curl_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_UPLOAD is related to the behavior of CURLOPT_POSTFIELDS. If CURLOPT_POSTFIELDS is set first and then CURLOPT_SAFE_UPLOAD is 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 use curl_setopt()single-shot setting CURLOPT_POSTFIELDS until just before curl_exec().

In fact, in the array used by curl_setopt_array(), it is guaranteed that the position of CURLOPT_POSTFIELDS is also reliable at the back. PHP's associative arrays are sequentially guaranteed. We can also assume that the internal execution order of curl_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 using class_exists() to determine the existence of CURLFile, it is recommended to write \CURLFile to 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!

Statement:
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