HTTP in PHP spool_ Case analysis of server configuration and usage

Time:2021-4-20

In this paper, an example is given to show how to use HTTP in PHP spool_ The configuration and usage of server. The details are as follows:

A spool is provided for us in spool_ http_ Server class, convenient for us to handle HTTP requests.

However, its support for HTTP protocol is not complete, so it is generally recommended to add a layer of nginx to the front for proxy, and the processing of PHP files should be handled by spool.

1、 Create a simple HTTP service

<?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、 Processing static files

Swoole has built two configuration parameters for us, which can be realized by simple configuration.

However, the function is simple, not recommended to use outside the network, there is a need to achieve their own.

<?php
$server = new swoole_http_server('0.0.0.0', 8888);
 
$server->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、 Process file upload

<?php
//Create an HTTP server service
$server = new swoole_http_server('0.0.0.0', 8888);
 
$server->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();

Let’s create one in the statistics directory upload.html File:

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  < title > file upload
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="upload" value="">
  < input type = submit "value = submit" >
</form>
</body>
</html>

4、 Processing route file auto loading

<?php
//Create an HTTP server service
$server = new swoole_http_server('0.0.0.0', 8888);
 
$server->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();

We create the test directory under the directory SRC and create the test.php file


<?php
namespace Test;
 
class Test
{
  public function test()
  {
    return 'test';
  }
}

Then visit127.0.0.1:8888/test/test/test You can see the returned results.

adopt$request->server['path_info']To find the module, controller, method, and then register our own load function, import the file. Instantiate the class object, then invoke the method and return the result.

Be careful not to put SPL_ autoload_ Register is placed in the OnStart event callback function.

In OnStart callback, only echo, print log and modify process name are allowed. Do not perform other operations.

For more information about PHP, readers who are interested in it can see the following topics: summary of PHP network programming skills, summary of PHP socket usage, introductory course of PHP object-oriented programming, tutorial of PHP data structure and algorithm, and summary of PHP programming algorithm

I hope this article is helpful for PHP programming.

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]