Parse body from PUT method
@source https://gist.github.com/chlab/4283560

@return array data and files
487258
function parseBody()
    {
        $result = array(
            'data'=>array(),
            'files'=>array(),
            );

         // read incoming data
        $input = Instance::get('BODY');

        // grab multipart boundary from content type header
        preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);

        // content type is probably regular form-encoded
        if (!count($matches)) {
            // we expect regular puts to containt a query string containing data
            parse_str($input, $result['data']);
        } else {
            $boundary = $matches[1];
            // split content by boundary and get rid of last -- element
            $a_blocks = preg_split("/-+$boundary/", $input);
            array_pop($a_blocks);

            // loop data blocks
            foreach ($a_blocks as $id => $block) {
                if (empty($block))
                    continue;
                // you'll have to var_dump $block to understand this and maybe replace \n or \r with a visibile char
                // parse uploaded files
                if (strpos($block, 'application/octet-stream') !== FALSE) {
                    // match "name", then everything after "stream" (optional) except for prepending newlines
                    // preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
                    // $a_data['files'][$matches[1]] = isset($matches[2])?$matches[2]:null;
                }
                // parse all other fields
                else {
                    // match "name" and optional value in between newline sequences
                    if (strpos($block, 'filename="')===false) {
                        preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
                        $result['data'][$matches[1]] = isset($matches[2])?$matches[2]:null;
                    } else {
                        preg_match('/; name=\"([^\"]*)\"; filename=\"([^\"]*)\"\s*Content\-Type: ([\w\/]+)[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
                        $result['files'][$matches[1]] = array(
                            'name' => $matches[2],
                            'type' => $matches[3],
                            'tmp_name' => tempnam( ini_get( 'upload_tmp_dir' ), 'php' ),
                            'error' => UPLOAD_ERR_OK,
                            'size' => 0);
                        $result['files'][$matches[1]]['size'] = file_put_contents($result['files'][$matches[1]]['tmp_name'], $matches[4]);
                        $result['files'][$matches[1]]['size']!==false || $result['files'][$matches[1]]['error'] = UPLOAD_ERR_CANT_WRITE;
                    }
                }
            }
        }

        return $result;
    }
1346053
protected function _parsePostData() {
        $postData = $this->getRequest()->getRawBody();
        if (!$postData) {
            return array();
        }
        try {
            $postData = Zend_Json::decode($postData);
        } catch (Zend_Json_Exception $e) {
            throw new Garp_Content_Api_Rest_Exception(
                sprintf(Garp_Content_Api_Rest::EXCEPTION_INVALID_JSON, $e->getMessage())
            );
        }
        return $postData;
    }
1005570
def _put_or_post_multipart(self, method, url, data):
        
        fields = []
        files = []
        for key, value in data.items():
            if type(value) == file:
                files.append((key, value.name, value.read()))
            else:
                fields.append((key, value))
        content_type, body = _encode_multipart_formdata(fields, files)
        if self.parsed_endpoint.scheme == 'https':
            h = httplib.HTTPS(self.parsed_endpoint.netloc)
        else:
            h = httplib.HTTP(self.parsed_endpoint.netloc)
        h.putrequest(method, url)
        h.putheader('Content-Type', content_type)
        h.putheader('Content-Length', str(len(body)))
        h.putheader('Accept', 'application/json')
        h.putheader('User-Agent', USER_AGENT)
        h.putheader(API_TOKEN_HEADER_NAME, self.api_token)
        if self.api_version in ['0.1', '0.01a']:
            h.putheader(API_VERSION_HEADER_NAME, self.api_version)
        h.endheaders()
        h.send(body)
        errcode, errmsg, headers = h.getreply()
        if errcode not in [200, 202]:
            raise IOError('Response to %s to URL %s was status code %s: %s' % (method, url, errcode, h.file.read()))
        return json.loads(h.file.read())
680500
public function useFileGetContents()
    {
        $return  = [];
        $options = [
            'http' => [
                'method'  => $this->method,
                'timeout' => $this->timeout
            ]
        ];

        if ($this->isSSL) {
            // use SSL
            $options['ssl'] = [
                'verify_peer'      => $this->verifyPeer,
                'verify_peer_name' => $this->verifyPeer
            ];
        }

        $headers = $this->getHeaderArray();

        if (count($headers) > 0) {
            $options['http']['header'] = implode("\r\n", $headers);
        }

        if ($this->method == 'POST') {
            $post = $this->getPostBody();
            if (mb_strlen($post) > 0) {
                $options['http']['content'] = $post;
            }
            $return['post'] = $post;
        }
        $context      = stream_context_create($options);
        $query_string = $this->getQueryString();
        $this->debug->debug(__FUNCTION__, 'Options into Request: ', $options);
        $this->debug->debug(__FUNCTION__, 'Data Query String into Request: ', $query_string);
        $this->debug->debug(__FUNCTION__, 'Endpoint URL into Request: ', $this->url);
        try {
            $response          = file_get_contents($this->url . $query_string, FALSE, $context);
            $responseHeaders   = $http_response_header;
            $return['headers'] = $this->parseReturnHeaders($responseHeaders);
            $return['url']     = $this->url . $query_string;
            if ($response) {
                $return['content'] = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($response));
                if ($this->isJson === TRUE && $this->isDecodeJson === TRUE) {
                    $responseJson = json_decode(trim($return['content']));
                    if (json_last_error() == JSON_ERROR_NONE) {
                        $return['content'] = $responseJson;
                        $this->debug->debug(__FUNCTION__, 'Set Response is Json: ', $return['content']);
                    }
                }
            }
        }

        catch (Exception $e) {
            $return['error'] = [
                'code'     => 500,
                'message'  => 'Could not file_get_contents.',
                'extended' => $e
            ];
            $this->debug->error(__FUNCTION__, 'Could not file_get_contents: ', $return['error']);
        }

        if (isset($return['headers']['reponse_code'])) {
            $responseType = substr($return['headers']['reponse_code'], 0, 1);
            if ($responseType != '2') {
                $return['error'] = [
                    'code'    => $return['headers']['reponse_code'],
                    'message' => 'Server returned an error.'
                ];
                $this->debug->error(__FUNCTION__, 'Could not file_get_contents: ', $return['error']);
            }
        }

        $cookies = [];
        foreach ($http_response_header as $hdr) {
            if (preg_match('/^Set-Cookie:\s*([^;]+)/i', $hdr, $matches)) {
                parse_str($matches[1], $tmp);
                $cookies += $tmp;
            }
        }

        if ($this->trackCookies) {
            $cookies       = array_merge($this->cookies, $cookies);
            $this->cookies = $cookies;
        }
        $return['cookies'] = $cookies;
        $this->debug->info(__FUNCTION__, 'Final Result from Server: ', $return);

        return $return;
    }
292946
protected function parseDataFromResponse()
    {
        $content = $this->rawResponse->body;
        $xml = simplexml_load_string($content);
        if (isset($xml->UploadId)) {
            return strval($xml->UploadId);
        }
        throw new OssException("cannot get UploadId");
    }
1220747
public function body() {
        $event = [];
        if (!empty($this->replyToken)) {
            $event['replyToken'] = $this->replyToken;
        }
        $event['type'] = $this->eventType();
        $event['timestamp'] = time();
        $event['source'] = $this->source;
        $event['message'] = $this->message;
        $result = ['events' => [$event]];
        return json_encode($result);
    }
683406
function file_body() {
    $lines = array();
    $lines['name'] =  $this->component_data['readable_name'];
    $lines['description'] =  $this->component_data['short_description'];
    if (!empty( $this->component_data['module_dependencies'])) {
      // For lines which form a set with the same key and array markers,
      // simply make an array.
      foreach ( $this->component_data['module_dependencies'] as $dependency) {
        $lines['dependencies'][] = $dependency;
      }
    }

    if (!empty( $this->component_data['module_package'])) {
      $lines['package'] =  $this->component_data['module_package'];
    }

    $lines['core'] = "7.x";

    if (!empty($this->extraLines)) {
      // Add a blank line before the extra lines.
      $lines[] = '';
      $lines = array_merge($lines, $this->extraLines);
    }

    $info = $this->process_info_lines($lines);
    return $info;
  }
1312490
private function parseArray()
    {
        $length = $this->parseUnsignedInt32();
        $stopAt = strlen($this->buffer) - $length;
        $array = [];

        while (strlen($this->buffer) > $stopAt) {
            $array[] = $this->parseField();
        }

        return $array;
    }
157012
protected function parseDataFromResponse()
    {
        $content = $this->rawResponse->body;
        $config = new WebsiteConfig();
        $config->parseFromXml($content);
        return $config;
    }
135642
protected function parseMeetupApiData()
    {
        $responseBody = $this->parseBodyContent();

        $this->data = $responseBody['results'];
        $this->metadata = $responseBody['meta'];
    }
1235697
protected function parseParsedBody()
    {
        $contentType = $this->getHeaderLine(RequestHeader::CONTENT_TYPE);
        // post
        if('POST' === $this->method && in_array($contentType, [
            MediaType::APPLICATION_FORM_URLENCODED,
            MediaType::MULTIPART_FORM_DATA,
        ]))
        {
            $this->parsedBody = $this->post;
        }
        // json
        else if(in_array($contentType, [
            MediaType::APPLICATION_JSON,
            MediaType::APPLICATION_JSON_UTF8,
        ]))
        {
            $this->parsedBody = json_decode($this->body, !Config::get('@currentServer.jsonBodyIsObject', false));
        }
        // xml
        else if(in_array($contentType, [
            MediaType::TEXT_XML,
            MediaType::APPLICATION_ATOM_XML,
            MediaType::APPLICATION_RSS_XML,
            MediaType::APPLICATION_XHTML_XML,
            MediaType::APPLICATION_XML,
        ]))
        {
            $this->parsedBody = new \DOMDocument();
            $this->parsedBody->loadXML($this->body);
        }
        // 其它
        else
        {
            $this->parsedBody = (object)(string)$this->body;
        }
    }
1272995
private function parsePut()
    {
        $contentType = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : 'application/x-www-form-urlencoded';

        $tmp = explode(';', $contentType);
        $boundary = '';
        $encoding = '';

        $contentType = array_shift($tmp);

        foreach ($tmp as $t) {
            if (strpos($t, 'boundary') !== false) {
                $t = explode('=', $t, 2);
                if (isset($t[1])) {
                    $boundary = '--' . $t[1];
                }
            } elseif (strpos($t, 'charset') !== false) {
                $t = explode('=', $t, 2);
                if (isset($t[1])) {
                    $encoding = $t[1];
                }
            }
            if ($boundary !== '' && $encoding !== '') {
                break;
            }
        }

        switch ($contentType) {
            case 'multipart/form-data':
                #grab multipart boundary from content type header
                if (!empty($boundary)) {
                    break;
                }
                $contentType = 'application/x-www-form-urlencoded';
            // Fallthrough intentional - no boundary supplied with multipart content-type, so treat as url encoded
            case 'application/x-www-form-urlencoded':
                parse_str(file_get_contents($this->unitTestRequestFile ?: 'php://input'), $_POST);
                return;
            default:
                return;
        }

        $_FILES = [];
        $_POST = [];
        $chunkLength = 8096;
        $raw_headers = '';

        $stream = fopen($this->unitTestRequestFile ?: 'php://input', 'rb');

        $sanity = fgets($stream, strlen($boundary) + 5);

        // Skip initial blank line
        if ($sanity == "\r\n") {
            $sanity = fgets($stream, strlen($boundary) + 5);
        }

        if (rtrim($sanity) !== $boundary) {
            #malformed file, boundary should be first item
            return;
        }

        while (($chunk = fgets($stream)) !== false) {
            if ($chunk === $boundary) {
                continue;
            }

            if (rtrim($chunk) == '') { #blank line means we have all the headers and are going to read content
                $raw_headers = explode("\r\n", $raw_headers);
                $headers = [];
                $matches = [];

                foreach ($raw_headers as $header) {
                    if (strpos($header, ':') === false) {
                        continue;
                    }
                    list($name, $value) = explode(':', $header, 2);
                    $headers[strtolower($name)] = ltrim($value, ' ');
                }

                $raw_headers = '';

                if (!isset($headers['content-disposition'])) {
                    continue;
                }

                $filename = null;
                preg_match(
                    '/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
                    $headers['content-disposition'],
                    $matches
                );
                list(, $type, $name) = $matches;

                #process data
                if (isset($matches[4])) { #pull in file
                    $error = UPLOAD_ERR_OK;

                    $filename = $matches[4];
                    $filename_parts = pathinfo($filename);
                    $contentType = 'unknown';

                    if (isset($headers['content-type'])) {
                        $tmp = explode(';', $headers['content-type']);
                        $contentType = $tmp[0];
                    }

                    $tmpnam = tempnam(ini_get('upload_tmp_dir'), 'php');
                    $fileHandle = fopen($tmpnam, 'wb');


                    if ($fileHandle === false) {
                        $error = UPLOAD_ERR_CANT_WRITE;
                    } else {
                        $lastLine = null;
                        while (($chunk = fgets($stream, $chunkLength)) !== false && strpos($chunk, $boundary) !== 0) {
                            if ($lastLine !== null) {
                                if (fwrite($fileHandle, $lastLine) === false) {
                                    $error = UPLOAD_ERR_CANT_WRITE;
                                    break;
                                }
                            }
                            $lastLine = $chunk;
                        }

                        if ($lastLine !== null && $error !== UPLOAD_ERR_CANT_WRITE) {
                            if (fwrite($fileHandle, rtrim($lastLine, "\r\n")) === false) {
                                $error = UPLOAD_ERR_CANT_WRITE;
                            }
                        }
                    }

                    $_FILES[$name] = [
                        'name' => $filename,
                        'type' => $contentType,
                        'tmp_name' => $tmpnam,
                        'error' => $error,
                        'size' => filesize($tmpnam)
                    ];

                    continue;
                } else { #pull in variable
                    $fullValue = '';
                    $lastLine = null;
                    while (($chunk = fgets($stream)) !== false && strpos($chunk, $boundary) !== 0) {
                        if ($lastLine !== null) {
                            $fullValue .= $lastLine;
                        }

                        $lastLine = $chunk;
                    }

                    if ($lastLine !== null) {
                        $fullValue .= rtrim($lastLine, "\r\n");
                    }

                    if (isset($headers['content-type'])) {
                        $tmp = explode(';', $headers['content-type']);
                        $encoding = '';

                        foreach ($tmp as $t) {
                            if (strpos($t, 'charset') !== false) {
                                $t = explode($t, '=', 2);
                                if (isset($t[1])) {
                                    $encoding = $t[1];
                                }
                                break;
                            }
                        }

                        if ($encoding !== '' && strtoupper($encoding) !== 'UTF-8' && strtoupper($encoding) !== 'UTF8') {
                            $tmp = mb_convert_encoding($fullValue, 'UTF-8', $encoding);
                            if ($tmp !== false) {
                                $fullValue = $tmp;
                            }
                        }

                    }

                    $fullValue = $name . '=' . $fullValue;
                    $origName = $name;
                    $tmp = [];
                    parse_str($fullValue, $tmp);
                    $_POST = $this->recursiveSetter($origName, $_POST, $tmp);
                }
                continue;
            }

            $raw_headers .= $chunk;
        }

        $GLOBALS['_PUT'] = $_POST;
        fclose($stream);
    }
43962
protected function parseDataFromResponse()
    {
        $xml = new \SimpleXMLElement($this->rawResponse->body);
        $encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : "";
        $objectList = $this->parseObjectList($xml, $encodingType);
        $prefixList = $this->parsePrefixList($xml, $encodingType);
        $bucketName = isset($xml->Name) ? strval($xml->Name) : "";
        $prefix = isset($xml->Prefix) ? strval($xml->Prefix) : "";
        $prefix = OssUtil::decodeKey($prefix, $encodingType);
        $marker = isset($xml->Marker) ? strval($xml->Marker) : "";
        $marker = OssUtil::decodeKey($marker, $encodingType);
        $maxKeys = isset($xml->MaxKeys) ? intval($xml->MaxKeys) : 0;
        $delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : "";
        $delimiter = OssUtil::decodeKey($delimiter, $encodingType);
        $isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : "";
        $nextMarker = isset($xml->NextMarker) ? strval($xml->NextMarker) : "";
        $nextMarker = OssUtil::decodeKey($nextMarker, $encodingType);
        return new ObjectListInfo($bucketName, $prefix, $marker, $nextMarker, $maxKeys, $delimiter, $isTruncated, $objectList, $prefixList);
    }
949867
function file_body() {
    $args = func_get_args();
    $files = array_shift($args);

    $module_data = $this->component_data;
    //print_r($module_data);

    $lines = array();
    $lines['name'] = $module_data['readable_name'];
    $lines['type'] = $module_data['base'];
    $lines['description'] = $module_data['short_description'];
    if (!empty($module_data['module_dependencies'])) {
      // For lines which form a set with the same key and array markers,
      // simply make an array.
      foreach ($module_data['module_dependencies'] as $dependency) {
        $lines['dependencies'][] = $dependency;
      }
    }

    if (!empty($module_data['module_package'])) {
      $lines['package'] = $module_data['module_package'];
    }

    $lines['core'] = "8.x";

    if (!empty($this->extraLines)) {
      $lines = array_merge($lines, $this->extraLines);
    }

    $info = $this->process_info_lines($lines);
    return $info;
  }
1112390
protected function buildBody() {
		
		// If we are uploading files, we have to build the request body manually since the stupid syntax for file uploads
		// will break non-file values beginning with '@'. When we no longer support PHP 5.4 we can just turn this syntax off
		// and use CurlFile.

		if (count($this->files())) {
			$body = [];
			foreach ($this->params as $key => $value) {
				$body[] = implode("\r\n", ["Content-Disposition: form-data; name=\"{$key}\"", "", $value]);
			}
			foreach ($this->files as $key => $path) {
				$file = new File($path);
				$body[] = implode("\r\n", ["Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file->name()}\"", "Content-Type: application/octet-stream", "", $file->contents()]);
			}

			do {
				$boundary = "---------------------" . md5(mt_rand() . microtime());
			} while (preg_grep("/{$boundary}/", $body));
			foreach ($body as $i => $part) {
				$body[$i] = "--{$boundary}\r\n" . $part;
			}
			$body[] = "--{$boundary}--";
			$body[] = "";

			curl_setopt($this->curl, CURLOPT_POSTFIELDS, implode("\r\n", $body));
			$this->header('Content-Type', 'multipart/form-data; boundary=' . $boundary);
		} else {
			curl_setopt($this->curl, CURLOPT_POSTFIELDS, http_build_query($this->params));
			$this->header('Content-Type', 'application/x-www-form-urlencoded');
		}
	}
769096
public function getParsedBody()
    {
        if ($this->parsedBody !== false) {
            return $this->parsedBody;
        }

        $mediaType = $this->getMediaType();

        $parts = explode('+', $mediaType);
        if (count($parts) >= 2) {
            $mediaType = 'application/' . $parts[count($parts) - 1];
        }
        unset($parts);

        if (isset($this->bodyParsers[$mediaType])) {
            $body = (string) $this->getBody();
            $parsed = $this->bodyParsers[$mediaType]($body);

            $this->parsedBody = $parsed;

            unset($parsed, $body, $mediaType);

            return $this->parsedBody;
        }

        return null;
    }
768706
protected function prepareParsedBody()
    {
        if ($this->method == self::METHOD_POST &&
            in_array($this->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data'])
        ) {
            return $_POST;
        } else {
            $body = (string)$this->getBody();

            switch ($this->getMediaType()) {
                case 'application/json':
                    return json_decode($body, true);

                case 'application/xml':
                    return simplexml_load_string($body);

                default:
                    parse_str($body, $output);

                    return $output;
            }
        }
    }