Swoole\Response::getHeader PHP Method

getHeader() public method

public getHeader ( $fastcgi = false )
    function getHeader($fastcgi = false)
    {
        $out = '';
        if ($fastcgi) {
            $out .= 'Status: ' . $this->http_status . ' ' . self::$HTTP_HEADERS[$this->http_status] . "\r\n";
        } else {
            //Protocol
            if (isset($this->head[0])) {
                $out .= $this->head[0] . "\r\n";
                unset($this->head[0]);
            } else {
                $out = "HTTP/1.1 200 OK\r\n";
            }
        }
        //fill header
        if (!isset($this->head['Server'])) {
            $this->head['Server'] = Swoole\Protocol\WebServer::SOFTWARE;
        }
        if (!isset($this->head['Content-Type'])) {
            $this->head['Content-Type'] = 'text/html; charset=' . \Swoole::$charset;
        }
        if (!isset($this->head['Content-Length'])) {
            $this->head['Content-Length'] = strlen($this->body);
        }
        //Headers
        foreach ($this->head as $k => $v) {
            $out .= $k . ': ' . $v . "\r\n";
        }
        //Cookies
        if (!empty($this->cookie) and is_array($this->cookie)) {
            foreach ($this->cookie as $v) {
                $out .= "Set-Cookie: {$v}\r\n";
            }
        }
        //End
        $out .= "\r\n";
        return $out;
    }

Usage Example

Example #1
0
 /**
  * 发送响应
  * @param $request Swoole\Request
  * @param $response Swoole\Response
  * @return bool
  */
 function response(Swoole\Request $request, Swoole\Response $response)
 {
     if (!isset($response->head['Date'])) {
         $response->head['Date'] = gmdate("D, d M Y H:i:s T");
     }
     if (!isset($response->head['Connection'])) {
         //keepalive
         if ($this->keepalive and (isset($request->head['Connection']) and strtolower($request->head['Connection']) == 'keep-alive')) {
             $response->head['KeepAlive'] = 'on';
             $response->head['Connection'] = 'keep-alive';
         } else {
             $response->head['KeepAlive'] = 'off';
             $response->head['Connection'] = 'close';
         }
     }
     //过期命中
     if ($this->expire and $response->http_status == 304) {
         $out = $response->getHeader();
         return $this->server->send($request->fd, $out);
     }
     //压缩
     if ($this->gzip) {
         $response->head['Content-Encoding'] = 'deflate';
         $response->body = gzdeflate($response->body, $this->config['server']['gzip_level']);
     }
     $out = $response->getHeader() . $response->body;
     $ret = $this->server->send($request->fd, $out);
     $this->afterResponse($request, $response);
     return $ret;
 }