WebServer.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. namespace Workerman;
  3. use \Workerman\Worker;
  4. use \Workerman\Protocols\Http;
  5. use \Workerman\Protocols\HttpCache;
  6. /**
  7. *
  8. * 基于Worker实现的一个简单的WebServer
  9. * HTTP协议
  10. *
  11. * @author walkor <walkor@workerman.net>
  12. */
  13. class WebServer extends Worker
  14. {
  15. /**
  16. * 默认mime类型
  17. * @var string
  18. */
  19. protected static $defaultMimeType = 'text/html; charset=utf-8';
  20. /**
  21. * 服务器名到文件路径的转换
  22. * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
  23. */
  24. protected $serverRoot = array();
  25. /**
  26. * mime类型映射关系
  27. * @var array
  28. */
  29. protected static $mimeTypeMap = array();
  30. /**
  31. * 添加站点域名与站点目录的对应关系,类似nginx的
  32. * @param string $domain
  33. * @param string $root_path
  34. * @return void
  35. */
  36. public function addRoot($domain, $root_path)
  37. {
  38. $this->serverRoot[$domain] = $root_path;
  39. }
  40. /**
  41. * 构造函数
  42. * @param string $socket_name
  43. * @param array $context_option
  44. */
  45. public function __construct($socket_name, $context_option = array())
  46. {
  47. $this->onWorkerStart = array($this, 'onWorkerStart');
  48. $this->onMessage = array($this, 'onMessage');
  49. $this->name = 'WebServer';
  50. list($scheme, $address) = explode(':', $socket_name, 2);
  51. parent::__construct('http:'.$address, $context_option);
  52. }
  53. /**
  54. * 进程启动的时候一些初始化工作
  55. * @throws \Exception
  56. */
  57. public function onWorkerStart()
  58. {
  59. if(empty($this->serverRoot))
  60. {
  61. throw new \Exception('server root not set, please use WebServer::addRoot($domain, $root_path) to set server root path');
  62. }
  63. // 初始化HttpCache
  64. HttpCache::init();
  65. // 初始化mimeMap
  66. $this->initMimeTypeMap();
  67. }
  68. /**
  69. * 初始化mimeType
  70. * @return void
  71. */
  72. public function initMimeTypeMap()
  73. {
  74. $mime_file = Http::getMimeTypesFile();
  75. if(!is_file($mime_file))
  76. {
  77. $this->notice("$mime_file mime.type file not fond");
  78. return;
  79. }
  80. $items = file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  81. if(!is_array($items))
  82. {
  83. $this->log("get $mime_file mime.type content fail");
  84. return;
  85. }
  86. foreach($items as $content)
  87. {
  88. if(preg_match("/\s*(\S+)\s+(\S.+)/", $content, $match))
  89. {
  90. $mime_type = $match[1];
  91. $extension_var = $match[2];
  92. $extension_array = explode(' ', substr($extension_var, 0, -1));
  93. foreach($extension_array as $extension)
  94. {
  95. self::$mimeTypeMap[$extension] = $mime_type;
  96. }
  97. }
  98. }
  99. }
  100. /**
  101. * 当接收到完整的http请求后的处理逻辑
  102. * 1、如果请求的是以php为后缀的文件,则尝试加载
  103. * 2、如果请求的url没有后缀,则尝试加载对应目录的index.php
  104. * 3、如果请求的是非php为后缀的文件,尝试读取原始数据并发送
  105. * 4、如果请求的文件不存在,则返回404
  106. * @param TcpConnection $connection
  107. * @param mixed $data
  108. * @return void
  109. */
  110. public function onMessage($connection, $data)
  111. {
  112. // 请求的文件
  113. $url_info = parse_url($_SERVER['REQUEST_URI']);
  114. if(!$url_info)
  115. {
  116. Http::header('HTTP/1.1 400 Bad Request');
  117. return $connection->close('<h1>400 Bad Request</h1>');
  118. }
  119. $path = $url_info['path'];
  120. $path_info = pathinfo($path);
  121. $extension = isset($path_info['extension']) ? $path_info['extension'] : '' ;
  122. if($extension == '')
  123. {
  124. $path = ($len = strlen($path)) && $path[$len -1] == '/' ? $path.'index.php' : $path . '/index.php';
  125. $extension = 'php';
  126. }
  127. $root_dir = isset($this->serverRoot[$_SERVER['HTTP_HOST']]) ? $this->serverRoot[$_SERVER['HTTP_HOST']] : current($this->serverRoot);
  128. $file = "$root_dir/$path";
  129. // 对应的php文件不存在则直接使用根目录的index.php
  130. if($extension == 'php' && !is_file($file))
  131. {
  132. $file = "$root_dir/index.php";
  133. }
  134. // 请求的文件存在
  135. if(is_file($file))
  136. {
  137. // 判断是否是站点目录里的文件
  138. if((!($request_realpath = realpath($file)) || !($root_dir_realpath = realpath($root_dir))) || 0 !== strpos($request_realpath, $root_dir_realpath))
  139. {
  140. Http::header('HTTP/1.1 400 Bad Request');
  141. return $connection->close('<h1>400 Bad Request</h1>');
  142. }
  143. $file = realpath($file);
  144. // 如果请求的是php文件
  145. if($extension == 'php')
  146. {
  147. $cwd = getcwd();
  148. chdir($root_dir);
  149. ini_set('display_errors', 'off');
  150. // 缓冲输出
  151. ob_start();
  152. // 载入php文件
  153. try
  154. {
  155. // $_SERVER变量
  156. $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
  157. $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
  158. include $file;
  159. }
  160. catch(\Exception $e)
  161. {
  162. // 如果不是exit
  163. if($e->getMessage() != 'jump_exit')
  164. {
  165. echo $e;
  166. }
  167. }
  168. $content = ob_get_clean();
  169. ini_set('display_errors', 'on');
  170. $connection->close($content);
  171. chdir($cwd);
  172. return ;
  173. }
  174. // 请求的是静态资源文件
  175. if(isset(self::$mimeTypeMap[$extension]))
  176. {
  177. Http::header('Content-Type: '. self::$mimeTypeMap[$extension]);
  178. }
  179. else
  180. {
  181. Http::header('Content-Type: '. self::$defaultMimeType);
  182. }
  183. // 获取文件信息
  184. $info = stat($file);
  185. $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
  186. // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
  187. if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
  188. {
  189. // 文件没有更改则直接304
  190. if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
  191. {
  192. // 304
  193. Http::header('HTTP/1.1 304 Not Modified');
  194. // 发送给客户端
  195. return $connection->close('');
  196. }
  197. }
  198. if($modified_time)
  199. {
  200. Http::header("Last-Modified: $modified_time");
  201. }
  202. // 发送给客户端
  203. return $connection->close(file_get_contents($file));
  204. }
  205. else
  206. {
  207. // 404
  208. Http::header("HTTP/1.1 404 Not Found");
  209. return $connection->close('<html><head><title>404 页面不存在</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
  210. }
  211. }
  212. }