start_web.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. require_once __DIR__.'/../../vendor/workerman/workerman/Worker.php';
  15. use Workerman\Worker;
  16. use Workerman\Protocols\Http\Request;
  17. use Workerman\Protocols\Http\Response;
  18. use Workerman\Connection\TcpConnection;
  19. require_once __DIR__ . '/../../vendor/autoload.php';
  20. // WebServer
  21. $web = new Worker("http://0.0.0.0:55151");
  22. // WebServer进程数量
  23. $web->count = 2;
  24. define('WEBROOT', __DIR__ . DIRECTORY_SEPARATOR . 'Web');
  25. $web->onMessage = function (TcpConnection $connection, Request $request) {
  26. $_GET = $request->get();
  27. $path = $request->path();
  28. if ($path === '/') {
  29. $connection->send(exec_php_file(WEBROOT.'/index.php'));
  30. return;
  31. }
  32. $file = realpath(WEBROOT. $path);
  33. if (false === $file) {
  34. $connection->send(new Response(404, array(), '<h3>404 Not Found</h3>'));
  35. return;
  36. }
  37. // Security check! Very important!!!
  38. if (strpos($file, WEBROOT) !== 0) {
  39. $connection->send(new Response(400));
  40. return;
  41. }
  42. if (\pathinfo($file, PATHINFO_EXTENSION) === 'php') {
  43. $connection->send(exec_php_file($file));
  44. return;
  45. }
  46. $if_modified_since = $request->header('if-modified-since');
  47. if (!empty($if_modified_since)) {
  48. // Check 304.
  49. $info = \stat($file);
  50. $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
  51. if ($modified_time === $if_modified_since) {
  52. $connection->send(new Response(304));
  53. return;
  54. }
  55. }
  56. $connection->send((new Response())->withFile($file));
  57. };
  58. function exec_php_file($file) {
  59. \ob_start();
  60. // Try to include php file.
  61. try {
  62. include $file;
  63. } catch (\Exception $e) {
  64. echo $e;
  65. }
  66. return \ob_get_clean();
  67. }
  68. // 如果不是在根目录启动,则运行runAll方法
  69. if(!defined('GLOBAL_START'))
  70. {
  71. Worker::runAll();
  72. }