start.php 1.7 KB

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