start_web.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Protocols\Http\Request;
  4. use Workerman\Protocols\Http\Response;
  5. use Workerman\Connection\TcpConnection;
  6. include __DIR__ . '/vendor/autoload.php';
  7. // 启动一个webserver,用于吐html css js,方便展示
  8. // 这个webserver服务不是必须的,可以将这些html css js文件放到你的项目下用nginx或者apache跑
  9. $web = new Worker('http://0.0.0.0:2123');
  10. $web->name = 'web';
  11. define('WEBROOT', __DIR__ . DIRECTORY_SEPARATOR . 'web');
  12. $web->onMessage = function (TcpConnection $connection, Request $request) {
  13. $path = $request->path();
  14. if ($path === '/') {
  15. $connection->send(exec_php_file(WEBROOT.'/index.html'));
  16. return;
  17. }
  18. $file = realpath(WEBROOT. $path);
  19. if (false === $file) {
  20. $connection->send(new Response(404, array(), '<h3>404 Not Found</h3>'));
  21. return;
  22. }
  23. // Security check! Very important!!!
  24. if (strpos($file, WEBROOT) !== 0) {
  25. $connection->send(new Response(400));
  26. return;
  27. }
  28. if (\pathinfo($file, PATHINFO_EXTENSION) === 'php') {
  29. $connection->send(exec_php_file($file));
  30. return;
  31. }
  32. $if_modified_since = $request->header('if-modified-since');
  33. if (!empty($if_modified_since)) {
  34. // Check 304.
  35. $info = \stat($file);
  36. $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
  37. if ($modified_time === $if_modified_since) {
  38. $connection->send(new Response(304));
  39. return;
  40. }
  41. }
  42. $connection->send((new Response())->withFile($file));
  43. };
  44. function exec_php_file($file) {
  45. \ob_start();
  46. // Try to include php file.
  47. try {
  48. include $file;
  49. } catch (\Exception $e) {
  50. echo $e;
  51. }
  52. return \ob_get_clean();
  53. }
  54. if(!defined('GLOBAL_START'))
  55. {
  56. Worker::runAll();
  57. }