search
HomeBackend DevelopmentPHP Tutorial思考 PHP 5.0~5.6 各版本兼容性的 cURL 文件上传-干货【被坑过】

考虑 PHP 5.0~5.6 各版本兼容性的 cURL 文件上传--干货【被坑过】

没事不要读PHP的官方中文文档!版本跟不上坑死你!

不同版本PHP之间cURL的区别

PHP的cURL支持通过给CURL_POSTFIELDS传递关联数组(而不是字符串)来生成multipart/form-data的POST请求。

传统上,PHP的cURL支持通过在数组数据中,使用“@+文件全路径”的语法附加文件,供cURL读取上传。这与命令行直接调用cURL程序的语法是一致的:

<code style="font-family: Consolas, Menlo, Monaco, 'Courier New', monospace; padding: 0px; color: inherit; border-radius: 0px; white-space: inherit; background-color: transparent;">curl_setopt(ch, CURLOPT_POSTFIELDS, <span class="hljs-keyword" style="color: #859900;">array</span>(    <span class="hljs-string" style="color: #2aa198;">'file'</span> => <span class="hljs-string" style="color: #2aa198;">'@'</span>.realpath(<span class="hljs-string" style="color: #2aa198;">'image.png'</span>), )); equals$ curl -F <span class="hljs-string" style="color: #2aa198;">"file=@/absolute/path/to/image.png"</span> <url></code>

但PHP从5.5开始引入了新的CURLFile类用来指向文件。CURLFile类也可以详细定义MIME类型、文件名等可能出现在multipart/form-data数据中的附加信息。PHP推荐使用CURLFile替代旧的@语法:

<code style="font-family: Consolas, Menlo, Monaco, 'Courier New', monospace; padding: 0px; color: inherit; border-radius: 0px; white-space: inherit; background-color: transparent;">curl_setopt(ch, CURLOPT_POSTFIELDS, [    <span class="hljs-string" style="color: #2aa198;">'file'</span> => <span class="hljs-keyword" style="color: #859900;">new</span> CURLFile(realpath(<span class="hljs-string" style="color: #2aa198;">'image.png'</span>)), ]); </code>

PHP 5.5另外引入了CURL_SAFE_UPLOAD选项,可以强制PHP的cURL模块拒绝旧的@语法,仅接受CURLFile式的文件。5.5的默认值为false,5.6的默认值为true。

但是坑的一点在于:@语法在5.5就已经被打了deprecated,在5.6中就直接被删除了(会产生 ErorException: The usage of the?@filename?API for file uploading is deprecated. Please use the CURLFile class instead)。

对于PHP 5.6+而言,手动设置CURL_SAFE_UPLOAD为false是毫无意义的。根本不是字面意义理解的“设置成false,就能开启旧的unsafe的方式”——旧的方式已经作为废弃语法彻底不存在了。PHP 5.6+ == CURLFile only,不要有任何的幻想。

我的部署环境是5.4(仅@语法),但开发环境是5.6(仅CURLFile)。都没有压在5.5这个两者都支持过渡版本上,结果就是必须写出带有环境判断的两套代码。

现在问题来了……(挖掘机滚远点!)

环境判断:小心魔法数字!

我见过这种环境判断的代码:

<code style="font-family: Consolas, Menlo, Monaco, 'Courier New', monospace; padding: 0px; color: inherit; border-radius: 0px; white-space: inherit; background-color: transparent;"><span class="hljs-keyword" style="color: #859900;">if</span> (version_compare(phpversion(), <span class="hljs-string" style="color: #2aa198;">'5.4.0'</span>) >= <span class="hljs-number" style="color: #2aa198;">0</span>)</code>

我对这种代码的评价只有一个字:

这个判断掉入了典型的魔法数字陷阱。版本号莫名其妙的出现在代码之中,不查半天PHP手册和更新历史,很难明白作者被卡在了哪个功能的变更上。

代码应该回归本源。我们的实际需求其实是:有CURLFile就优先采用,没有再退化到传统@语法。那么代码就来了:

<code style="font-family: Consolas, Menlo, Monaco, 'Courier New', monospace; padding: 0px; color: inherit; border-radius: 0px; white-space: inherit; background-color: transparent;"><span class="hljs-keyword" style="color: #859900;">if</span> (class_exists(<span class="hljs-string" style="color: #2aa198;">'\CURLFile'</span>)) {    <span class="hljs-variable" style="color: #b58900;">$field</span> = <span class="hljs-keyword" style="color: #859900;">array</span>(<span class="hljs-string" style="color: #2aa198;">'fieldname'</span> => <span class="hljs-keyword" style="color: #859900;">new</span> \CURLFile(realpath(<span class="hljs-variable" style="color: #b58900;">$filepath</span>)));} <span class="hljs-keyword" style="color: #859900;">else</span> {    <span class="hljs-variable" style="color: #b58900;">$field</span> = <span class="hljs-keyword" style="color: #859900;">array</span>(<span class="hljs-string" style="color: #2aa198;">'fieldname'</span> => <span class="hljs-string" style="color: #2aa198;">'@'</span> . realpath(<span class="hljs-variable" style="color: #b58900;">$filepath</span>));}</code>

建议明确指定的退化选项

从可靠的角度,推荐指定CURL_SAFE_UPLOAD的值,明确告知php是容忍还是禁止旧的@语法。注意在低版本PHP中CURLOPT_SAFE_UPLOAD常量本身可能不存在,需要判断:

<code style="font-family: Consolas, Menlo, Monaco, 'Courier New', monospace; padding: 0px; color: inherit; border-radius: 0px; white-space: inherit; background-color: transparent;"><span class="hljs-keyword" style="color: #859900;">if</span> (class_exists(<span class="hljs-string" style="color: #2aa198;">'\CURLFile'</span>)) {    curl_<span class="hljs-built_in" style="color: #268bd2;">setopt</span>(<span class="hljs-variable" style="color: #b58900;">$ch</span>, CURLOPT_SAFE_UPLOAD, <span class="hljs-literal" >true</span>);} <span class="hljs-keyword" style="color: #859900;">else</span> {    <span class="hljs-keyword" style="color: #859900;">if</span> (defined(<span class="hljs-string" style="color: #2aa198;">'CURLOPT_SAFE_UPLOAD'</span>)) {        curl_<span class="hljs-built_in" style="color: #268bd2;">setopt</span>(<span class="hljs-variable" style="color: #b58900;">$ch</span>, CURLOPT_SAFE_UPLOAD, <span class="hljs-literal" >false</span>);    }}</code>

cURL选项设置的顺序

不管是curl_setopt()单发还是curl_setopt_array()批量,cURL的选项总是设置一个生效一个,而设置好的选项立刻就会影响cURL在设置后续选项时的行为。

例如CURLOPT_SAFE_UPLOAD就和CURLOPT_POSTFIELDS的行为有关。如果先设置CURLOPT_POSTFIELDS再设置CURLOPT_SAFE_UPLOAD,那么后者的约束作用就不会生效。因为设置前者时cURL就已经把数据实际的识读处理完毕了!

cURL有那么几个选项存在这种坑,务必小心。还好这种存在“依赖关系”的选项不多,机制也不复杂,简单处理即可。我的方法是先批量设置所有的选项,然后直到curl_exec()的前一刻才用curl_setopt()单发设置CURLOPT_POSTFIELDS

实际上在curl_setopt_array()用的数组中,保证CURLOPT_POSTFIELDS的位置在后边也是可靠的。PHP的关联数组是有顺序保障的,我们也可以假设curl_setopt_array()内部的执行顺序一定是从头到尾按顺序[注A],所以尽可放心。

我的做法只是在代码表现上加个多余的保险,突出强调顺序的重要性防以后手贱。

命名空间

PHP 5.2或以下的版本没有命名空间。代码中用到了空间分隔符\就会引发解析器错误。要照顾PHP 5.2其实容易想,放弃命名空间即可。

要注意的反倒是有命名空间的PHP 5.3+。无论是调用CURLFile还是用class_exists()判断CURLFile的存在性,都推荐写成\CURLFile明确指定顶层空间,防止代码包裹在命名空间内的时候崩掉。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software