start.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. use Adapterman\Adapterman;
  3. use Workerman\Worker;
  4. use Workerman\Lib\Timer;
  5. require_once __DIR__ . '/vendor/autoload.php';
  6. Adapterman::init();
  7. // WebServer
  8. $web = new Worker("http://0.0.0.0:8080");
  9. $web->count = (int) shell_exec('nproc') * 4;
  10. $web->name = 'workerman';
  11. define('WEBROOT', '/php/');
  12. $web->onWorkerStart = static function () {
  13. Header::init();
  14. };
  15. $web->onMessage = static function ($connection) {
  16. $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  17. /* if ($path === '/') {
  18. $connection->send(exec_php_file(WEBROOT.'/index.php', $request));
  19. return;
  20. } */
  21. $file = realpath(WEBROOT . $path);
  22. if (false === $file || !str_ends_with($file, '.php')) {
  23. http_response_code(404);
  24. $connection->send('<h3>404 Not Found</h3>');
  25. return;
  26. }
  27. // Security check!
  28. if (!str_starts_with($file, WEBROOT)) {
  29. http_response_code(400);
  30. $connection->send('<h3>400 Bad Request</h3>');
  31. return;
  32. }
  33. header(Header::$date); // To pass the bench
  34. $connection->send(exec_php_file($file));
  35. };
  36. function exec_php_file($file)
  37. {
  38. ob_start();
  39. // Try to include php file.
  40. try {
  41. include $file;
  42. } catch (Throwable $t) {
  43. echo $t;
  44. }
  45. return ob_get_clean();
  46. }
  47. class Header
  48. {
  49. const NAME = 'Date: ';
  50. /**
  51. * Date header
  52. *
  53. * @var string
  54. */
  55. public static $date;
  56. public static function init(): void
  57. {
  58. self::$date = self::NAME . gmdate('D, d M Y H:i:s').' GMT';
  59. Timer::add(1, static function() {
  60. self::$date = self::NAME . gmdate('D, d M Y H:i:s').' GMT';
  61. });
  62. }
  63. }
  64. Worker::runAll();