WebServer.php 7.9 KB

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