Swoole\Http\Parser::parseHeader PHP Method

parseHeader() static public method

头部解析
static public parseHeader ( $data ) : array
$data
return array
    static function parseHeader($data)
    {
        $header = array();
        $header[0] = array();
        $meta =& $header[0];
        $parts = explode("\r\n\r\n", $data, 2);
        // parts[0] = HTTP头;
        // parts[1] = HTTP主体,GET请求没有body
        $headerLines = explode("\r\n", $parts[0]);
        // HTTP协议头,方法,路径,协议[RFC-2616 5.1]
        list($meta['method'], $meta['uri'], $meta['protocol']) = explode(' ', $headerLines[0], 3);
        //错误的HTTP请求
        if (empty($meta['method']) or empty($meta['uri']) or empty($meta['protocol'])) {
            return false;
        }
        unset($headerLines[0]);
        //解析Header
        $header = array_merge($header, self::parseHeaderLine($headerLines));
        return $header;
    }

Usage Example

Example #1
0
 protected function checkHeader($client_id, $http_data)
 {
     //新的连接
     if (!isset($this->requests[$client_id])) {
         if (!empty($this->buffer_header[$client_id])) {
             $http_data = $this->buffer_header[$client_id] . $http_data;
         }
         //HTTP结束符
         $ret = strpos($http_data, self::HTTP_EOF);
         //没有找到EOF,继续等待数据
         if ($ret === false) {
             return false;
         } else {
             $this->buffer_header[$client_id] = '';
             $request = new Request();
             //GET没有body
             list($header, $request->body) = explode(self::HTTP_EOF, $http_data, 2);
             $request->head = $this->parser->parseHeader($header);
             //使用head[0]保存额外的信息
             $request->meta = $request->head[0];
             unset($request->head[0]);
             //保存请求
             $this->requests[$client_id] = $request;
             //解析失败
             if ($request->head == false) {
                 $this->log("parseHeader failed. header=" . $header);
                 return false;
             }
         }
     } else {
         $request = $this->requests[$client_id];
         $request->body .= $http_data;
     }
     return $request;
 }
All Usage Examples Of Swoole\Http\Parser::parseHeader