


The difference between cURL between different versions of PHP (-Experience), different versions of curl_PHP tutorial
Jul 12, 2016 am 08:52 AMThe difference between cURL between different versions of PHP (-Experience), different versions of curl
I used to make a collection tool to realize the collection of articles and save the pictures. .The content of the article is saved in the database, and the image needs to be uploaded to the image server first, and then the image address is returned and the image address of the article is replaced.
Here comes the problem: everything can be collected successfully, but the local test is normal, and the pictures can be uploaded successfully, but there are no pictures in the production environment. Then I debugged step by step, and found that the data is there, but Why can’t I upload pictures successfully during production?
After struggling for a few days, after reading the code step by step, debugging, and Baidu, I finally found the answer. What a big pitfall.
Use curl post to upload to the image server,
PHP’s cURL supports generating POST requests for CURL_POSTFIELDS
by passing an associative array (instead of a string) to multipart/form-data
.
Traditionally, PHP's cURL supports attaching files by using the "@
full file 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:
<code>curl_setopt(ch, CURLOPT_POSTFIELDS, <span class="hljs-keyword">array( <span class="hljs-string">'file' => <span class="hljs-string">'@'.realpath(<span class="hljs-string">'image.png'), )); equals $ curl -F <span class="hljs-string">"file=@/absolute/path/to/image.png" <url> </span></span></span></span></span></code>
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:
<code>curl_setopt(ch, CURLOPT_POSTFIELDS, [ <span class="hljs-string">'file' => <span class="hljs-keyword">new CURLFile(realpath(<span class="hljs-string">'image.png')), ]); </span></span></span></code>
PHP 5.5 also introduces the CURL_SAFE_UPLOAD
option, which can force 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 "setting it to false will 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 my 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 with the magic numbers!
I have seen this kind of environment judgment code:
<code><span class="hljs-keyword">if (version_compare(phpversion(), <span class="hljs-string">'5.4.0') >= <span class="hljs-number">0) </span></span></span></code>
I only have one word for this kind of code: 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 go back to its roots. Our actual needs are actually: use CURLFile first, without regressing to the traditional @
syntax. Then the code is here:
<code><span class="hljs-keyword">if (class_exists(<span class="hljs-string">'\CURLFile')) { <span class="hljs-variable">$field = <span class="hljs-keyword">array(<span class="hljs-string">'fieldname' => <span class="hljs-keyword">new \CURLFile(realpath(<span class="hljs-variable">$filepath))); } <span class="hljs-keyword">else { <span class="hljs-variable">$field = <span class="hljs-keyword">array(<span class="hljs-string">'fieldname' => <span class="hljs-string">'@' . realpath(<span class="hljs-variable">$filepath)); } </span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Explicitly specified degradation options are recommended
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 in lower versions of PHP, the CURLOPT_SAFE_UPLOAD
constant itself may not exist and needs to be judged:
<code><span class="hljs-keyword">if (class_exists(<span class="hljs-string">'\CURLFile')) { curl_<span class="hljs-built_in">setopt(<span class="hljs-variable">$ch, CURLOPT_SAFE_UPLOAD, <span class="hljs-literal">true); } <span class="hljs-keyword">else { <span class="hljs-keyword">if (defined(<span class="hljs-string">'CURLOPT_SAFE_UPLOAD')) { curl_<span class="hljs-built_in">setopt(<span class="hljs-variable">$ch, CURLOPT_SAFE_UPLOAD, <span class="hljs-literal">false); } } </span></span></span></span></span></span></span></span></span></span></span></code>
The order of cURL option settings
Whether it is curl_setopt()
single or curl_setopt_array()
batch, cURL’s options always take effect one by one, and the set options will immediately affect the behavior of cURL when setting subsequent options.
For example, CURLOPT_SAFE_UPLOAD
is related to CURLOPT_POSTFIELDS
’s behavior. If CURLOPT_POSTFIELDS
is set first and then CURLOPT_SAFE_UPLOAD
is set, the latter's 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 options in batches first, and then use curl_exec()
single settingscurl_setopt()
until just before CURLOPT_POSTFIELDS
.
In fact, in the array used by curl_setopt_array()
, it is guaranteed that the position of CURLOPT_POSTFIELDS
is reliable at the end. PHP’s associative arrays are sequence guaranteed. We can also assume that the internal execution order of curl_setopt_array()
must be sequential from beginning to end[注A]
, so you can rest assured.
My approach is just to add extra insurance to the code performance, highlighting the importance of order to prevent future mistakes.
Namespace
PHP 5.2 or below does 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 that PHP 5.3 has namespaces. Whether you are 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.
Okay, this hole is quite deep, so I’ll share it when I jump out.
(The above solutions are reproduced from the website, thank you for letting me find your article!)

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

Is DAI suitable for long-term holding? The answer depends on individual needs and risk preferences. 1. DAI is a decentralized stablecoin, generated by excessive collateral for crypto assets, suitable for users who pursue censorship resistance and transparency; 2. Its stability is slightly inferior to USDC, and may experience slight deansal due to collateral fluctuations; 3. Applicable to lending, pledge and governance scenarios in the DeFi ecosystem; 4. Pay attention to the upgrade and governance risks of MakerDAO system. If you pursue high stability and compliance guarantees, it is recommended to choose USDC; if you attach importance to the concept of decentralization and actively participate in DeFi applications, DAI has long-term value. The combination of the two can also improve the security and flexibility of asset allocation.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

USDC is safe. It is jointly issued by Circle and Coinbase. It is regulated by the US FinCEN. Its reserve assets are US dollar cash and US bonds. It is regularly audited independently, with high transparency. 1. USDC has strong compliance and is strictly regulated by the United States; 2. The reserve asset structure is clear, supported by cash and Treasury bonds; 3. The audit frequency is high and transparent; 4. It is widely accepted by institutions in many countries and is suitable for scenarios such as DeFi and compliant payments. In comparison, USDT is issued by Tether, with an offshore registration location, insufficient early disclosure, and reserves with low liquidity assets such as commercial paper. Although the circulation volume is large, the regulatory recognition is slightly low, and it is suitable for users who pay attention to liquidity. Both have their own advantages, and the choice should be determined based on the purpose and preferences of use.
