• 技术文章 >后端开发 >php教程

    PHP的POST方式

    2016-05-19 15:12:03原创661

    对比表单POST和fsockopen提交两种不同方式的区别。

    表单POST方式提交情况下

    $_POST 与 php://input可以取到值,$HTTP_RAW_POST_DATA 为空
    $_POST 以关联数组方式组织提交的数据,并对此进行编码处理,如urldecode,甚至编码转换。
    php://input 可通过输入流以文件读取方式取得未经处理的POST原始数据

    php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。php://input 不能用于 enctype="multipart/form-data"。

    fsockopen提交POST数据
    例:

    $sock = fsockopen("localhost", 80, $errno, $errstr, 30);
    if (!$sock) die("$errstr ($errno)\n");
    $data = "txt=" . urlencode("中") . "&bar=" . urlencode("Value for Bar");
    fwrite($sock, "POST /posttest/response.php HTTP/1.0\r\n");
    fwrite($sock, "Host: localhost\r\n");
    fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
    fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
    fwrite($sock, "Accept: */*\r\n");
    fwrite($sock, "\r\n");
    fwrite($sock, "$data\r\n");
    fwrite($sock, "\r\n");
    $headers = "";
    while ($str = trim(fgets($sock, 4096)))
       $headers .= "$str\n";
    echo "\n";
    $body = "";
    while (!feof($sock))
       $body .= fgets($sock, 4096);
    fclose($sock);
    echo $body;

    与(一)结果一致

    结论:
    1. 用php://input可以很便捷的取到原始POST数据

    2. $HTTP_RAW_POST_DATA 仅在POST的Content-Type类型不为PHP识别时才有效

    如通常通过页面表单提交后的POST数据,不能通过$HTTP_RAW_POST_DATA提取到。因其编码类型属性(enctype属性)为 application/x-www-form-urlencoded、multipart/form-data。

    注:即使在页面内显性地改变enctype属性为PHP不可识别的类型,仍无效。
    因表单提交编码属性是表单限定,不可识别的类型将被认为按默认编码方式提交(即application/x-www-form-urlencoded)

    3. $_POST仅当数据按 application/x-www-form-urlencoded 类型提交时才能得到。

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:PHP的POST方式
    上一篇:PHP集成FCK的函数代码 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 手写PHP API框架(二)之Composer的安装使用• 设计API接口时,要注意这些地方!• PHP8.3要有新函数了!(json_validate函数说明)• 聊聊PHP escapeshellarg函数使用的中文问题• PHP原生类的总结分享
    1/1

    PHP中文网