Рубрики
Uncategorized

HTTP в PHP spool_ Анализ конфигурации и использования сервера

Автор оригинала: David Wong.

В этой статье приведен пример, показывающий, как использовать HTTP в очереди PHP Для настройки и использования сервера. Подробности заключаются в следующем:

Для нас предусмотрена катушка в классе сервера spool_ http_, удобная для обработки HTTP-запросов.

Однако его поддержка протокола HTTP не завершена, поэтому обычно рекомендуется добавить слой nginx для прокси-сервера, а обработка PHP-файлов должна выполняться с помощью spool.

1. Создайте простую службу HTTP

php
//Create an HTTP server service
$server = new swoole_http_server('0.0.0.0', 8888);
 
$server->set([
  'package_max_length' => 1024 * 1024 * 10,
  //Set the temporary directory for file upload
  'upload_tmp_dir' => __DIR__ . '/uploads/',
]);
 
//Set request event callback
//The function has two arguments:
// swoole_ http_ Request object, responsible for HTTP request related information
// swoole_ http_ The response object is responsible for responding to relevant information to the client
$server->on('request', function (swoole_http_request $request, swoole_http_response $response) {
  //Request header information
  var_dump($request->header);
 
  //Request related server information, equivalent to PHP$_ SERVER
  var_dump($request->server);
 
  //The get parameter of the request is equivalent to that in PHP$_ GET
  var_dump($request->get);
 
  //The post parameter of the request is equivalent to that in PHP$_ POST
  var_dump($request->post);
 
  //Requested cookie information
  var_dump($request->cookie);
 
  //File upload information, file size does not exceed package_ max_ The value of length
  var_dump($request->files);
 
  // Get the original post request data, which is equivalent to fopen (' php :// input ');
  var_dump($request->rawContent());
 
  //Get complete HTTP request message
  var_dump($request->getData());
 
  //Send information to client
  $response->end('hello');
});
 
// Start the service
$server->start();

2, Обработка статических файлов

Swool создал для нас два параметра конфигурации, которые могут быть реализованы с помощью простой конфигурации.

Однако функция проста, не рекомендуется использовать вне сети, есть необходимость добиваться своего самостоятельно.

set([
  //Configure static file root directory
  'document_root' => __DIR__ . '/statics/',
  //Enable the static file request processing function, so that when the request is a static file, spool will automatically search and return in the directory configured above
  'enable_static_handler' => true,
]);
 
$server->on('request', function ($request, $response) {
 
});
 
$server->start();

3, Загрузка файла процесса

set([
  //The file upload size does not exceed this value
  'package_max_length' => 1024 * 1024 * 50,
  //Set the temporary directory for file upload
  'upload_tmp_dir' => __DIR__ . '/tmp/',
  'upload_dir' => __DIR__ . '/uploads/',
  'document_root' => __DIR__ . '/statics/',
  'enable_static_handler' => true,
]);
 
$server->on('request', function ($request, $response) use ($server) {
  if ($request->server['path_info'] == '/upload') {
    $tmp = $request->files['upload']['tmp_name'];
    $upload = $server->setting['upload_dir'] . $request->files['upload']['name'];
    if (file_exists($tmp) &&
      move_uploaded_file($tmp, $upload)) {
      $response->header('Content-Type', 'text/html; charset=UTF-8');
      $response - > end ('upload succeeded ');
    } else {
      $ response -> end (' Upload failed ');
    }
  }
});
 
// Start the service
$server->start();

Давайте создадим его в каталоге статистики upload.html Файл:





  
  < title > file upload


< input type = submit "value = submit" >

4、 Автоматическая загрузка файла маршрута обработки

set([
  //Directory of configuration items
  'project_path' => __DIR__ . '/src/',
]);
 
$server->on('WorkerStart', function ($server, $worker_id) {
  // Register autoloaders
  spl_autoload_register(function ($class) use($server) {
    $class = $server->setting['project_path'] . str_replace('\', DIRECTORY_SEPARATOR, $class) . '.php';
 
    if (file_exists($class)) {
      include_once $class;
    }
  });
});
 
$server->on('request', function ($request, $response) use ($server) {
  $pathInfo = explode('/', ltrim($request->server['path_info'], '/'));
 
  //Module / controller / method
  $module = $pathInfo[0] ?? 'Index';
  $controller = $pathInfo[1] ?? 'Index';
  $method = $pathInfo[2] ?? 'index';
 
  try {
    $class = "\{$module}\{$controller}";
    $result = (new $class)->{$method}();
    $response->end($result);
  } catch (\Throwable $e) {
    $response->end($e->getMessage());
  }
});
 
// Start the service
$server->start();

Мы создаем каталог тестов в каталоге SRC и создаем test.php файл

Затем посетите 127.0.0.1:8888/тест/тест/тест Вы можете увидеть возвращенные результаты.

примите $запрос->сервер['path_info'] Чтобы найти модуль, контроллер, метод, а затем зарегистрировать нашу собственную функцию загрузки, импортируйте файл. Создайте экземпляр объекта класса, затем вызовите метод и верните результат.

Будьте осторожны, чтобы не поместить регистр SPL_ autoload_ в функцию обратного вызова события OnStart.

При обратном вызове OnStart разрешены только эхо, печать журнала и изменение имени процесса. Не выполняйте других операций.

Для получения дополнительной информации о PHP читатели, интересующиеся им, могут ознакомиться со следующими темами: краткое описание навыков сетевого программирования PHP, краткое описание использования сокетов PHP, вводный курс объектно-ориентированного программирования PHP, учебник по структуре и алгоритму данных PHP, а также краткое описание алгоритма программирования PHP

Я надеюсь, что эта статья будет полезна для программирования на PHP.