public function redirect($location = null, $externalRedirect = false, $statusCode = 302) { $this->response->status($statusCode); $this->response->header('Location: ' . $location); $this->response->end(); return $this; }
function user_handshake(swoole_http_request $request, swoole_http_response $response) { //自定定握手规则,没有设置则用系统内置的(只支持version:13的) if (!isset($request->header['sec-websocket-key'])) { //'Bad protocol implementation: it is not RFC6455.' $response->end(); return false; } if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $request->header['sec-websocket-key']) || 16 !== strlen(base64_decode($request->header['sec-websocket-key']))) { //Header Sec-WebSocket-Key is illegal; $response->end(); return false; } $key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)); $headers = array('Upgrade' => 'websocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Accept' => $key, 'Sec-WebSocket-Version' => '13', 'KeepAlive' => 'off'); foreach ($headers as $key => $val) { $response->header($key, $val); } $response->status(101); $response->end(); global $server; $fd = $request->fd; $server->defer(function () use($fd, $server) { $server->push($fd, "hello, welcome\n"); }); return true; }
/** * @return string */ public function send() { $this->sendHeaders(); if ($this->body) { $this->swooleResponse->write($this->body); } $this->swooleResponse->end(); }
function no_chunk(swoole_http_request $request, swoole_http_response $response) { // try // { // if (rand(1, 99) % 2 == 1) // { // throw new Exception("just for fun."); // } // $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>"); // } // catch(Exception $e) // { // $response->end("<h1>Exceptiom</h1><div>".$e->getMessage()."</div>"); // } //var_dump($request); // var_dump($request->files); // var_dump($request->post); // var_dump($request->cookie); $response->end("<h1>Hello Swoole.</h1>"); return; //var_dump($request); // var_dump($_GET); //var_dump($_POST); //var_dump($_COOKIE); //$response->status(301); //$response->header("Location", "http://www.baidu.com/"); //$response->cookie("hello", "world", time() + 3600); // $response->header("Content-Type", "text/html; charset=utf-8"); //var_dump($request->rawContent()); //var_dump($request->post); // var_dump($request->get); // echo strlen(gzdeflate("<h1>Hello Swoole.</h1>")); // $response->end("<h1>Hello Swoole.</h1>"); //$response->end("<h1>Hello Swoole. #".str_repeat('A', rand(100, 999))."</h1>"); //global $http; //$http->task("hello world"); $file = realpath(__DIR__ . '/../' . $request->server['request_uri']); if (is_file($file)) { echo "http get file={$file}\n"; if (substr($file, -4) == '.php') { $response->gzip(); } else { $response->header('Content-Type', 'image/jpeg'); } $content = file_get_contents($file); echo "response size = " . strlen($content) . "\n"; // $response->write($content); // $response->end(); $response->end($content); } else { $response->end("<h1>Hello Swoole.</h1>"); } }
/** * 此函数只调用一次 * @param $data * @return $this|bool */ public function end($data) { if ($this->_endFlag) { return false; } if (is_null($data)) { $data = ''; } if ($this->_writeFlag) { $this->sw->write($data); $data = ''; } $this->sw->end($data); $this->_endFlag = true; return $this; }
function onRequest(\swoole_http_request $req, \swoole_http_response $resp) { $path = trim($req->server['request_uri'], '/'); if ($path == 'app/stats') { if ($req->server['request_method'] != 'POST') { $resp->status(403); $resp->end("<h1>No POST Data</h1>"); } else { $data = $req->rawContent(); $stats = gzdecode($data); if ($stats) { $this->insertToDb($stats); } else { $this->log("gzdecode failed, fd={$req->fd}, length={$req->header['content-length']}"); } $resp->end('{"code": 1}'); } } else { $resp->status(404); $resp->end("<h1>Page Not Found</h1>"); } }
public function onRequest(swoole_http_request $request, swoole_http_response $response) { $path_info = $request->server['path_info']; if ($path_info === '/shell.html') { $response->end(file_get_contents('shell.html')); } foreach ($this->server->connections as $connection) { $connection_info = $server->connection_info($connection); if (isset($connection_info['websocket_status']) && $connection_info['websocket_status'] == WEBSOCKET_STATUS_FRAME) { // ws connection $this->server->push($connection, json_encode($result)); } } }
/** * @param ResponseInterface $response * @param \swoole_http_response $swooleResponse */ public function reverseTransform(ResponseInterface $response, \swoole_http_response $swooleResponse) { foreach (array_keys($response->getHeaders()) as $name) { $swooleResponse->header($name, $response->getHeaderLine($name)); } $swooleResponse->status($response->getStatusCode()); $body = $response->getBody(); $body->rewind(); # workaround for https://bugs.php.net/bug.php?id=68948 while (false === $body->eof() && '' !== ($buffer = $body->read($this->responseBuffer))) { $swooleResponse->write($buffer); } $swooleResponse->end(); }
function doStatic(\swoole_http_request $req, \swoole_http_response $resp) { $file = $this->document_root . $req->server['request_uri']; $read_file = true; $fstat = stat($file); //过期控制信息 if (isset($req->header['if-modified-since'])) { $lastModifiedSince = strtotime($req->header['if-modified-since']); if ($lastModifiedSince and $fstat['mtime'] <= $lastModifiedSince) { //不需要读文件了 $read_file = false; $resp->status(304); } } else { $resp->header('Cache-Control', "max-age={$this->expire_time}"); $resp->header('Pragma', "max-age={$this->expire_time}"); $resp->header('Last-Modified', date(self::DATE_FORMAT_HTTP, $fstat['mtime'])); $resp->header('Expires', "max-age={$this->expire_time}"); } if ($read_file) { $extname = Swoole\Upload::getFileExt($file); if (empty($this->types[$extname])) { $mime_type = 'text/html; charset=' . $this->charest; } else { $mime_type = $this->types[$extname]; } $resp->header('Content-Type', $mime_type); $resp->sendfile($file); } else { $resp->end(); } return true; }
/** * 请求处理 * @param \swoole_http_request $request * @param \swoole_http_response $response * @return bool */ function request(\swoole_http_request $request, \swoole_http_response $response) { unset($_SERVER); unset($_COOKIE); try { $domain = $this->getHost($request); $hostPort = $domain . ':' . $this->getServerPort($request); $client_ip = $request->server['remote_addr']; if (function_exists('wd_decrypt')) { $postdata = $request->post; if (!empty($postdata)) { foreach ($postdata as $key => $val) { $data = wd_decrypt(wd_hextostr($key)); #$this->access_log(print_r($data,true)); $this->saveToRedis($data, $client_ip); } } else { $this->access_log(print_r($postdata, true)); } } else { $this->access_log('function wd_decrypt no exist'); } $m_st = memory_get_usage(); $response->end(""); } catch (Exception $e) { $this->ExceptionLog('执行异常' . $e->getMessage()); $this->responseErrCode($response, 500); } }
function doStatic(\swoole_http_request $req, \swoole_http_response $resp) { $file = $this->document_root . $req->server['request_uri']; $extname = Swoole\Upload::getFileExt($file); if (empty($this->types[$extname])) { $mime_type = 'text/html'; } else { $mime_type = $this->types[$extname]; } if (isset(self::$gzip_extname[$extname])) { $resp->gzip(); } $resp->header('Content-Type', $mime_type); $resp->end(file_get_contents($this->document_root . $req->server['request_uri'])); }
function no_chunk(swoole_http_request $request, swoole_http_response $response) { /** * Cookie Test */ //$response->cookie('test1', '1234', time() + 86400, '/'); // $response->cookie('test2', '5678', time() + 86400); // var_dump($response->cookie); // var_dump($request->cookie); // try // { // if (rand(1, 99) % 2 == 1) // { // throw new Exception("just for fun."); // } // $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>"); // } // catch(Exception $e) // { // $response->end("<h1>Exceptiom</h1><div>".$e->getMessage()."</div>"); // } //var_dump($request->server['request_uri'], substr($request->server['request_uri'], -4, 4)); if (substr($request->server['request_uri'], -8, 8) == 'test.jpg') { $response->header('Content-Type', 'image/jpeg'); $response->sendfile(dirname(__DIR__) . '/test.jpg'); return; } if ($request->server['request_uri'] == '/favicon.ico') { $response->status(404); $response->end(); return; } // else // { //var_dump($request->post); //var_export($request->cookie); // var_dump($request->rawContent()); // if ($request->server['request_method'] == 'POST') // { // var_dump($request->post); // } // echo "GET:" . var_export($_GET, true)."\n"; // echo "POST:" . var_export($_POST, true)."\n"; // echo "get:" . var_export($request->get, true)."\n"; // echo "post:" . var_export($request->post, true)."\n"; //var_dump($request->server); $output = ''; $output .= "<h2>HEADER:</h2>" . dump($request->header); $output .= "<h2>SERVER:</h2>" . dump($request->server); if (!empty($request->files)) { $output .= "<h2>FILE:</h2>" . dump($request->files); } if (!empty($request->cookie)) { $output .= "<h2>COOKIES:</h2>" . dump($request->cookie); } if (!empty($request->get)) { $output .= "<h2>GET:</h2>" . dump($request->get); } if (!empty($request->post)) { $output .= "<h2>POST:</h2>" . dump($request->post); } //$response->header('X-Server', 'Swoole'); //unset($request, $response); // swoole_timer_after(2000, function() use ( $response) { $response->end("<h1>Hello Swoole.</h1>" . $output); // }); // } return; //var_dump($request); // var_dump($_GET); //var_dump($_POST); //var_dump($_COOKIE); //$response->status(301); //$response->header("Location", "http://www.baidu.com/"); //$response->cookie("hello", "world", time() + 3600); // $response->header("Content-Type", "text/html; charset=utf-8"); //var_dump($request->post); // var_dump($request->get); // echo strlen(gzdeflate("<h1>Hello Swoole.</h1>")); // $response->end("<h1>Hello Swoole.</h1>"); //$response->end("<h1>Hello Swoole. #".str_repeat('A', rand(100, 999))."</h1>"); //global $http; //$http->task("hello world"); $file = realpath(__DIR__ . '/../' . $request->server['request_uri']); if (is_file($file)) { echo "http get file={$file}\n"; if (substr($file, -4) == '.php') { $response->gzip(); } else { $response->header('Content-Type', 'image/jpeg'); } $content = file_get_contents($file); echo "response size = " . strlen($content) . "\n"; // $response->write($content); // $response->end(); $response->end($content); } else { $response->end("<h1>Hello Swoole.</h1>"); } }
public final function onRequest(\swoole_http_request $request, \swoole_http_response $response) { //return the json foreach ($this->httpConfig['response_header'] as $k => $v) { $response->header($k, $v); } //forever http 200 ,when the error json code decide $response->status(200); //chenck post error if (!isset($request->post["params"])) { $response->end(json_encode(Packet::packFormat("Parameter was not set or wrong", 100003))); return; } //get the post parameter $params = $request->post; $params = json_decode($params["params"], true); //check the parameter need field if (!isset($params["guid"]) || !isset($params["api"]) || count($params["api"]) == 0) { $response->end(json_encode(Packet::packFormat("Parameter was not set or wrong", 100003))); return; } //task base info $task = array("guid" => $params["guid"], "fd" => $request->fd, "protocol" => "http"); $url = trim($request->server["request_uri"], "\r\n/ "); switch ($url) { case "api/multisync": $task["type"] = DoraConst::SW_MODE_WAITRESULT_MULTI; foreach ($params["api"] as $k => $v) { $task["api"] = $params["api"][$k]; $taskid = $this->server->task($task, -1, function ($serv, $task_id, $data) use($response) { $this->onHttpFinished($serv, $task_id, $data, $response); }); $this->taskInfo[$task["fd"]][$task["guid"]]["taskkey"][$taskid] = $k; } break; case "api/multinoresult": $task["type"] = DoraConst::SW_MODE_NORESULT_MULTI; foreach ($params["api"] as $k => $v) { $task["api"] = $params["api"][$k]; $this->server->task($task); } $pack = Packet::packFormat("transfer success.已经成功投递", 100001); $pack["guid"] = $task["guid"]; $response->end(json_encode($pack)); break; case "server/cmd": $task["type"] = DoraConst::SW_CONTROL_CMD; if ($params["api"]["cmd"]["name"] == "getStat") { $pack = Packet::packFormat("OK", 0, array("server" => $this->server->stats())); $pack["guid"] = $task["guid"]; $response->end(json_encode($pack)); return; } if ($params["api"]["cmd"]["name"] == "reloadTask") { $pack = Packet::packFormat("OK", 0, array('server' => $this->server->stats())); $this->server->reload(true); $pack["guid"] = $task["guid"]; $response->end(json_encode($pack)); return; } break; default: $response->end(json_encode(Packet::packFormat("unknow task type.未知类型任务", 100002))); unset($this->taskInfo[$task["fd"]]); return; } }
/** * 静态文件处理; * @param \swoole_http_request $request * @param \swoole_http_response $response * @return bool */ protected function doStaticFile($request, $response) { $pathInfo = $request->server['path_info']; if ($pathInfo == '/') { if (!empty($this->defaultFiles)) { foreach ($this->defaultFiles as $file) { $staticFile = $this->getStaticFile(DIRECTORY_SEPARATOR . $file); if (is_file($staticFile)) { $response->end(file_get_contents($staticFile)); return true; } } } } $staticFile = $this->getStaticFile($pathInfo); if (is_dir($staticFile)) { //是目录 foreach ($this->defaultFiles as $file) { if (is_file($staticFile . $file)) { $response->header('Content-Type', 'text/html'); $response->end(file_get_contents($staticFile . $file)); return true; } } } $ext = pathinfo($pathInfo, PATHINFO_EXTENSION); if (isset($this->mimes[$ext])) { //非法的扩展名 if (is_file($staticFile)) { //读取静态文件 $response->header('Content-Type', $this->mimes[$ext]); $response->end(file_get_contents($staticFile)); return true; } else { $response->status(404); $response->end(''); return true; } } return false; }