search
HomeBackend DevelopmentPHP Tutorialphp://input & $_POST & $HTTP_RAW_POST_DATA 的详解

        PHP 用于开发 webservice 的 API 接口与客户端做数据交互时不一定会使用 PHP 可以处理的数据格式进行通信,比如 API 常用的 json xml,在此场景下我们需要使用其他的方式获取客户端发来的数据然后进行处理,下面我们就实例模拟下客户端请求 PHP API 场景下的数据交互方式。

        同时要理解 get 请求并未携带表单数据,get 请求的本质是请求服务器的某一资源,其向服务器发送的数据都位于请求头的 Query String/Query Path 中,请求头是 uri,注意理解 get 请求的语意,是去服务器获取资源而不是向服务器发送“数据”。 post 请求则是载有 Form Data 即表单数据的, 是想服务器发送 “数据” 的

    get                                                                                  post

        

    可以看出get的参数都是附在请求头中,并不像post中有content-length /content-type /from data 这些描述请求携带的数据内容的属性值

php支持的数据类型

PHP 支持的数据格式(注意:这里说的支持不是指简单的获取到,意为可以进行自动处理,自动填充到 $_POST/ $_FILES中去,再次强调,get 请求并没有向服务器发送“数据”,它是取,不是存,所以 $_GET 的是参数而不是数据)

    application/x-www-form-urlencoded 普通的表单数据

    multipart/form-data 上传文件的表单 enctype="multipart/form-data"

PHP 不支持的数据格式

     application/json

     application/xml


不能处理但可以获取到,你可以自己手动处理,参照表



application/x-www-form-urlencoded multipart/form-data  application/json application/xml
php://input 可获取 不可获取 可获取 可获取
$_POST 可获取 可获取 不可获取 不可获取
$HTTP_RAW_POST_DATA 可获取 不可获取 可获取 可获取


PS: $HTTP_RAW_POST_DATA 已经被 PHP7 废弃,原因是 php://input 完全囊括了它的所有功能,且其对服务器的压力要比 php://input 大很多,最懦弱的是它默认配置下是让位 $_POST 的,如果 $_POST 能处理数据的话他就得靠边站,当然你可以配置 php.ini 将 always_populate_raw_post_data  配置项打开,则会一直填充其所能识别的数据,即便 $_POST 的也能处理。


PHP的数据处理方式

php://input: 除数据类型为 multipart/form-data 的不能识别外,其他格式都可以获取,而后我们可以根据数据类型处理

$_POST: 可以识别 application/x-www-form-urlencoded multipart/form-data 格式,json xml 无法识别

$HTTP_RAW_POST_DATA :识别能力与 php://input 相同,默认配置下与 $_POST 互斥且优先级低于 $_POST


实例

先贴出服务端代码

注意当发送的数据为 multipart/form-data 时 PHP 会将文件类型的数据存放在 $_FILES 中,文本的存放于 $_POST 中,但他们是同一组的,都是 from data 中的数据,与 $_GET 是不同的,$_GET 中填充的是请求头中 Query String 的参数

<?php/** * @author sallency * @date 2016-3-4 11:03:23 * @desc 简单模拟PHP作为API时如何处理各种格式的数据 */error_reporting(0);echo "==== 客户端发送的数据格式 =====" . PHP_EOL;echo "REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD'] . PHP_EOL;echo "ACCEPT: " . $_SERVER['HTTP_ACCEPT'] . PHP_EOL;echo "CONTENT_TYPE: " . ($_SERVER['CONTENT_TYPE'] ? $_SERVER['CONTENT_TYPE'] : "null") . PHP_EOL;echo PHP_EOL . "===== php://input 数据 ========" . PHP_EOL;echo file_get_contents('php://input') . PHP_EOL;echo PHP_EOL . '===== $_POST 数据 =============' . PHP_EOL;print_r($_POST);//当 multipart/form-data 类型时文件数据是存放在 $_FILES 中的 文本则 $_POST 中echo PHP_EOL . '===== $_FILES 数据 =============' . PHP_EOL;print_r($_FILES);echo PHP_EOL . '===== $HTTP_RAW_POST_DATA =====' . PHP_EOL;echo $HTTP_RAW_POST_DATA ? $HTTP_RAW_POST_DATA : 'null' . PHP_EOL;?>

1、发送 application/x-www-form-urlencoded 标准数据 

    

            可以看出 php://input 和  $_POST/$_FILES 里都能正常识别接收此类型的数据,其实 $_HTTP_RAW_POST_DATA 也能接受,但我们说过默认情况下它和 $_POST/$_FILES 是互斥且优先级低,所以 $_POST/$_FILES 中有数据时它就不会被填充了,可修改配置让他一直填充自己可识别的数据。

2、发送 multipart/form-data

    php://input 和 $HTTP_RAW_POST_DATA 为空,说明它俩无法识别此类行的数据流(其实也只是不能识别此类行的,其他的都没问题),$_POST/$_FILES 则可以正常识别

3、发送 application/json 格式

    

        数据体:   

        

    php://input 和 $HTTP_RAW_POST_DATA 可识别, $_POST 则无法识别

4、发送 application/xml 格式

       

            数据体:

               

            php://input 和 $HTTP_RAW_POST_DATA 可识别, $_POST 则无法识别

总结

        当然还有很多其他的数据类型我们就不做测试了,大家可以自己动手。

        application/x-www-form-urlencoded 是 PHP 的标准数据流类型, 可以被三者识别

        multipart/form-data 只能被 $_POST/$_FILES 识别处理,另外的两者无法识别

        application/json application/xml 等就只能被 php://input 和 $HTTP_RAW_POST_DATA 识别了,这也是我们日常开发接口时往往使用 php://input 数据输入流来获取客户端请求携带的数据

 

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
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor