start_web.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Protocols\Http\Request;
  4. use Workerman\Protocols\Http\Response;
  5. use Workerman\Connection\TcpConnection;
  6. // composer autoload
  7. require_once join(DIRECTORY_SEPARATOR, array(__DIR__, "..", "..", "vendor", "autoload.php"));
  8. $web = new Worker('http://0.0.0.0:2022');
  9. $web->name = 'web';
  10. define('WEBROOT', __DIR__ . DIRECTORY_SEPARATOR . 'public');
  11. $web->onMessage = function (TcpConnection $connection, Request $request) {
  12. $path = $request->path();
  13. if ($path === '/') {
  14. $connection->send(exec_php_file(WEBROOT.'/index.html'));
  15. return;
  16. }
  17. $file = realpath(WEBROOT. $path);
  18. if (false === $file) {
  19. $connection->send(new Response(404, array(), '<h3>404 Not Found</h3>'));
  20. return;
  21. }
  22. // Security check! Very important!!!
  23. if (strpos($file, WEBROOT) !== 0) {
  24. $connection->send(new Response(400));
  25. return;
  26. }
  27. if (\pathinfo($file, PATHINFO_EXTENSION) === 'php') {
  28. $connection->send(exec_php_file($file));
  29. return;
  30. }
  31. $if_modified_since = $request->header('if-modified-since');
  32. if (!empty($if_modified_since)) {
  33. // Check 304.
  34. $info = \stat($file);
  35. $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
  36. if ($modified_time === $if_modified_since) {
  37. $connection->send(new Response(304));
  38. return;
  39. }
  40. }
  41. $connection->send((new Response())->withFile($file));
  42. };
  43. function exec_php_file($file) {
  44. \ob_start();
  45. // Try to include php file.
  46. try {
  47. include $file;
  48. } catch (\Exception $e) {
  49. echo $e;
  50. }
  51. return \ob_get_clean();
  52. }
  53. if (!defined('GLOBAL_START')) {
  54. Worker::runAll();
  55. }