Table of Contents
The difference between cURL between different versions of PHP (-Experience), different versions of curl
Environmental judgment: Be careful with the magic numbers!
Explicitly specified degradation options are recommended
The order of cURL option settings
Namespace
Home Backend Development PHP Tutorial The difference between cURL between different versions of PHP (-Experience), different versions of curl_PHP tutorial

The difference between cURL between different versions of PHP (-Experience), different versions of curl_PHP tutorial

Jul 12, 2016 am 08:52 AM
curl php different the difference Version of

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

<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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1126175.htmlTechArticleThe difference between cURL between different versions of PHP (-Experience), different versions of curl were collected before Tool to save the collected articles and pictures. The content of the article is saved in the database...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

How to use XPath to search from a specified DOM node in JavaScript? How to use XPath to search from a specified DOM node in JavaScript? Apr 04, 2025 pm 11:15 PM

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"&gt; "Export"&gt; "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

See all articles