start_web.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. use Workerman\Worker;
  15. use Workerman\Protocols\Http\Request;
  16. use Workerman\Protocols\Http\Response;
  17. use Workerman\Connection\TcpConnection;
  18. require_once __DIR__ . '/../../vendor/autoload.php';
  19. // WebServer
  20. $web = new Worker("http://0.0.0.0:55151");
  21. // WebServer进程数量
  22. $web->count = 2;
  23. define('WEBROOT', __DIR__ . DIRECTORY_SEPARATOR . 'Web');
  24. $web->onMessage = function (TcpConnection $connection, Request $request) {
  25. $_GET = $request->get();
  26. $path = $request->path();
  27. if ($path === '/') {
  28. $connection->send(exec_php_file(WEBROOT.'/index.php'));
  29. return;
  30. }
  31. $file = realpath(WEBROOT. $path);
  32. if (false === $file) {
  33. $connection->send(new Response(404, array(), '<h3>404 Not Found</h3>'));
  34. return;
  35. }
  36. // Security check! Very important!!!
  37. if (strpos($file, WEBROOT) !== 0) {
  38. $connection->send(new Response(400));
  39. return;
  40. }
  41. if (\pathinfo($file, PATHINFO_EXTENSION) === 'php') {
  42. $connection->send(exec_php_file($file));
  43. return;
  44. }
  45. $if_modified_since = $request->header('if-modified-since');
  46. if (!empty($if_modified_since)) {
  47. // Check 304.
  48. $info = \stat($file);
  49. $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
  50. if ($modified_time === $if_modified_since) {
  51. $connection->send(new Response(304));
  52. return;
  53. }
  54. }
  55. $connection->send((new Response())->withFile($file));
  56. };
  57. function exec_php_file($file) {
  58. \ob_start();
  59. // Try to include php file.
  60. try {
  61. include $file;
  62. } catch (\Exception $e) {
  63. echo $e;
  64. }
  65. return \ob_get_clean();
  66. }
  67. // 如果不是在根目录启动,则运行runAll方法
  68. if(!defined('GLOBAL_START'))
  69. {
  70. Worker::runAll();
  71. }