PHP Curl File upload compatible php5.0~5.6 versions

Source: Internet
Author: User
Tags curl options curl upload file deprecated

PHP 5.0~5.6 Version-compatible curl file uploads

A recent need to upload files using php curl. Step on the pit a few, finishing as follows.

Different versions of PHP between curl differences

PHP's curl supports generating multipart/form-data post requests by passing associative arrays (rather than strings) to Curl_postfields.

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:

1 Array (2 ' file ' = ' @ '. Realpath 3  4equals5 $ curl-f "[Email protected]/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:

1 curl_setopt (CH, curlopt_postfields, [2new curlfile (realpath3  ]);

PHP 5.5 also introduces the Curl_safe_upload option, which forces PHP's Curl module to reject the old @ syntax and only accepts 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:

The @ syntax has been deprecated in 5.5 and has been deleted directly in 5.6 (will produce erorexception:the usage of the @filename API for file uploading is deprecated. Use the Curlfile class instead).

For PHP 5.6+, it is meaningless to manually set 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+ = = Curlfile only, 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:

1 if (version_compare(phpversion(), ' 5.4.0 ') >= 0)

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:

1 if (class_exists(' \curlfile ')) {2$fieldarraynew \curlfile ( Realpath ($filepath))); 3 Else {4$fieldarrayrealpath($filepath)); 5 }

Recommended for explicitly specified degradation options
From a reliable point of view, it is recommended to specify the value of Curl_safe_upload to explicitly tell PHP whether to tolerate or disallow the old @ syntax. Note that in the low version of PHP, the Curlopt_safe_upload constant itself may not exist and needs to be judged:

1 if(class_exists(' \curlfile ')) {2curl_setopt ($ch, Curlopt_safe_upload,true);3}Else {4 if(defined(' Curlopt_safe_upload ')) {5curl_setopt ($ch, Curlopt_safe_upload,false);6 }7}

The order in which the curl options are set
Whether it's a curl_setopt () or 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.

Curlopt_safe_upload, for example, is related to Curlopt_postfields's behavior. If you set Curlopt_postfields and then set 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 set the Curlopt_postfields with curl_setopt () only once before Curl_exec ().

In fact, in an array of Curl_setopt_array (), it is reliable to ensure that the position of the curlopt_postfields is behind. The associative array of PHP is guaranteed in sequence, and we can assume that the order of execution within the Curl_setopt_array () must be sequential [note a], 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 will cause 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 using class_exists () to determine the existence of the curlfile, it is recommended to write \curlfile explicitly specify the top-level space to prevent the code from collapsing when it is wrapped within the namespace.

The last compatible versions of the code are as follows:

1<?PHP2 3 /*http://localhost/upload.php:4 Print_r ($_post);5 Print_r ($_files);6 */7 8 $ch=curl_init ();9 Ten $filePath= '/home/vagrant/test.png '; One $data=Array(' name ' = ' Foo ', ' file ' = ' @ '.$filePath); A  - //compatible with 5.0-5.6 version of Curl - if(class_exists(' \curlfile ')) { the     $data[' file '] =New\curlfile (Realpath($filePath)); -}Else { -     if(defined(' Curlopt_safe_upload ')) { -curl_setopt ($ch, Curlopt_safe_upload,FALSE); +     } - } +  Acurl_setopt ($ch, Curlopt_url, ' http://localhost/test/curl/load_file.php '); atcurl_setopt ($ch, Curlopt_post, 1); -curl_setopt ($ch, Curlopt_postfields,$data); -  -Curl_exec ($ch); -?>

Related articles:

PHP Curl Upload file $_files empty issue

http://www.cnblogs.com/zqifa/p/php-curl-1.html

done!

PHP Curl File upload compatible php5.0~5.6 versions

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.