Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP“;php://input" 美元邮政_Php_Ajax_Input - Fatal编程技术网

PHP“;php://input" 美元邮政

PHP“;php://input" 美元邮政,php,ajax,input,Php,Ajax,Input,我已被指示使用该方法php://input当与来自JQuery的Ajax请求交互时,而不是$\u POST。我不明白的是,与使用$\u POST或$\u GET的全局方法相比,使用此方法的好处是什么 php://input可以为您提供数据的原始字节。如果发布的数据是JSON编码的结构,这非常有用,AJAX POST请求通常就是这样 这里有一个函数可以做到这一点: /** * Returns the JSON encoded POST data, if any, as an object

我已被指示使用该方法
php://input当与来自JQuery的Ajax请求交互时,
而不是
$\u POST
。我不明白的是,与使用
$\u POST
$\u GET
的全局方法相比,使用此方法的好处是什么

php://input
可以为您提供数据的原始字节。如果发布的数据是JSON编码的结构,这非常有用,AJAX POST请求通常就是这样

这里有一个函数可以做到这一点:

  /**
   * Returns the JSON encoded POST data, if any, as an object.
   * 
   * @return Object|null
   */
  private function retrieveJsonPostData()
  {
    // get the raw POST data
    $rawData = file_get_contents("php://input");

    // this returns null if not valid json
    return json_decode($rawData);
  }

$\u POST
数组在处理由传统POST提交的表单中的键值数据时更有用。仅当发布的数据采用公认的格式(通常为
application/x-www-form-urlencoded
)时,此功能才起作用(有关详细信息,请参阅)

如果post数据格式不正确,$\u post将不包含任何内容。然而php://input 将具有格式不正确的字符串

例如,有些ajax应用程序没有形成上传文件的正确post键值序列,只是将所有文件作为post数据转储,没有变量名或任何内容。
$\u POST将为空,$\u文件也为空,并且php://input 将包含以字符串形式写入的精确文件。

原因是
php://input
返回请求的HTTP头之后的所有原始数据,无论内容类型如何

PHP超全局
$\u POST
,只应包装

  • application/x-www-form-urlencoded
    (简单表单帖子的标准内容类型)或
  • 多部分/表单数据
    (主要用于文件上传)
这是因为只有这些内容类型才是有效的。因此,服务器和PHP传统上不希望接收任何其他内容类型(这并不意味着它们不能)

因此,如果您只是简单地发布一个好的旧HTML
表单
,请求看起来如下所示:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3
POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}
但是如果您经常使用Ajax,这个probaby还包括使用类型(string、int、bool)和结构(数组、对象)交换更复杂的数据,因此在大多数情况下JSON是最佳选择。但是带有JSON负载的请求看起来像这样:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3
POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}
现在的内容将是
application/json
(或者至少没有上述内容),因此PHP的
$\u POST
-包装器还不知道如何处理这个问题

数据仍然存在,您无法通过包装器访问它。因此,您需要使用
file\u get\u contents('php://input)
()


这也是访问XML数据或任何其他非标准内容类型的方式。

如何使用它的简单示例

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>


首先,介绍一下PHP的基本原理。 PHP并不是为了显式地为您提供处理HTTP请求的纯REST(GET、POST、PUT、PATCH、DELETE)接口

然而,
$\u服务器
$\u COOKIE
$\u POST
$\u GET
$\u文件
,以及该功能对于普通人/外行的需求非常有用

$\u POST
(和
$\u GET
)的最大隐藏优势是输入数据由PHP自动进行url解码。您甚至从未想过必须这样做,特别是对于标准
GET
请求中的查询字符串参数,或者与
POST
请求一起提交的HTTP正文数据

其他HTTP请求方法 研究底层HTTP协议及其各种请求方法的人逐渐了解到,有许多HTTP请求方法,包括经常引用的
PUT
PATCH
(不在Google的Apigee中使用)和
DELETE

在PHP中,当未使用
POST
时,没有用于获取HTTP请求正文数据的超全局函数或输入过滤器函数。罗伊·菲尔丁的弟子们要做什么?;-)

然而,你会学到更多。。。 这就是说,随着您对PHP编程知识的提高,并希望使用JavaScript的
XmlHttpRequest
对象(对于一些人来说是jQuery),您会发现这个方案的局限性

$\u POST
限制您在HTTP
内容类型
标题中使用两种媒体类型:

  • 应用程序/x-www-form-urlencoded
    ,以及
  • 多部分/表单数据
  • 因此,如果您希望将数据值发送到服务器上的PHP,并将其显示在
    $\u POST
    superglobal中,那么您必须将其显示在客户端,并将所述数据作为键/值对发送,这对于新手来说是一个不方便的步骤(特别是在试图确定URL的不同部分是否需要不同形式的URL编码时:正常、原始等)

    对于所有jQuery用户,
    $.ajax()
    方法在将JSON传输到服务器之前将其转换为URL编码的键/值对。您可以通过设置
    processData:false来覆盖此行为。只需阅读,不要忘了在内容类型标题中发送正确的媒体类型

    php://input但是 即使您使用
    php://input
    对于您的HTTP
    POST
    请求正文数据,它将
    multipart/form data
    的HTTP
    内容类型不起作用,这是您希望允许文件上载时在HTML表单上使用的内容类型

    <form enctype="multipart/form-data" accept-charset="utf-8" action="post">
        <input type="file" name="resume">
    </form>
    
    因此,如果你认真负责,你需要:

  • 流编码检测算法
  • 动态/运行时流过滤器定义算法(因为您无法事先知道开始编码)
  • 更新
    'convert.iconv.UTF-8/UTF-8'
    将强制所有内容转换为UTF-8,但您仍然必须考虑iconv库可能不知道如何翻译的字符。换句话说,您必须了解如何定义当字符无法翻译时要采取的操作
        /**
         * @method Post getPostData
         * @return array
         * 
         * Convert Content-Disposition to a post data
         */
        function getPostData() : array
        {
            // @var string $input
            $input = file_get_contents('php://input');
    
            // continue if $_POST is empty
            if (strlen($input) > 0 && count($_POST) == 0 || count($_POST) > 0) :
    
                $postsize = "---".sha1(strlen($input))."---";
    
                preg_match_all('/([-]{2,})([^\s]+)[\n|\s]{0,}/', $input, $match);
    
                // update input
                if (count($match) > 0) $input = preg_replace('/([-]{2,})([^\s]+)[\n|\s]{0,}/', '', $input);
    
                // extract the content-disposition
                preg_match_all("/(Content-Disposition: form-data; name=)+(.*)/m", $input, $matches);
    
                // let's get the keys
                if (count($matches) > 0 && count($matches[0]) > 0)
                {
                    $keys = $matches[2];
    
                    foreach ($keys as $index => $key) :
                        $key = trim($key);
                        $key = preg_replace('/^["]/','',$key);
                        $key = preg_replace('/["]$/','',$key);
                        $key = preg_replace('/[\s]/','',$key);
                        $keys[$index] = $key;
                    endforeach;
    
                    $input = preg_replace("/(Content-Disposition: form-data; name=)+(.*)/m", $postsize, $input);
    
                    $input = preg_replace("/(Content-Length: )+([^\n]+)/im", '', $input);
    
                    // now let's get key value
                    $inputArr = explode($postsize, $input);
    
                    // @var array $values
                    $values = [];
    
                    foreach ($inputArr as $index => $val) :
                        $val = preg_replace('/[\n]/','',$val);
    
                        if (preg_match('/[\S]/', $val)) $values[$index] = trim($val);
    
                    endforeach;
    
                    // now combine the key to the values
                    $post = [];
    
                    // @var array $value
                    $value = [];
    
                    // update value
                    foreach ($values as $i => $val) $value[] = $val;
    
                    // push to post
                    foreach ($keys as $x => $key) $post[$key] = isset($value[$x]) ? $value[$x] : '';
    
                    if (is_array($post)) :
    
                        $newPost = [];
    
                        foreach ($post as $key => $val) :
    
                            if (preg_match('/[\[]/', $key)) :
    
                                $k = substr($key, 0, strpos($key, '['));
                                $child = substr($key, strpos($key, '['));
                                $child = preg_replace('/[\[|\]]/','', $child);
                                $newPost[$k][$child] = $val;
    
                            else:
    
                                $newPost[$key] = $val;
    
                            endif;
    
                        endforeach;
    
                        $_POST = count($newPost) > 0 ? $newPost : $post;
    
                    endif;
                }
    
            endif;
    
            // return post array
            return $_POST;
        }