PHPackages                             legionth/http-server-react - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. legionth/http-server-react

Abandoned → [react/http](/?search=react%2Fhttp)Library[HTTP &amp; Networking](/categories/http)

legionth/http-server-react
==========================

v0.5.0(9y ago)5283[5 issues](https://github.com/legionth/php-http-server-react/issues)MITPHPPHP &gt;=5.3

Since Dec 2Pushed 8y ago3 watchersCompare

[ Source](https://github.com/legionth/php-http-server-react)[ Packagist](https://packagist.org/packages/legionth/http-server-react)[ RSS](/packages/legionth-http-server-react/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (10)Versions (26)Used By (0)

legionth/http-server-react
==========================

[](#legionthhttp-server-react)

HTTP server written in PHP on top of ReactPHP.

**Table of Contents**

- [Usage](#usage)
    - [HttpServer](#httpserver)
        - [Create callback function](#create-a-callback-function)
    - [ChunkedDecoder](#chunkeddecoder)
    - [Handling exceptions](#handling-exceptions)
    - [Return type of the callback function](#return-type-of-the-callback-function)
    - [Middleware](#middleware)
        - [Creating your own middleware](#creating-your-own-middleware)
    - [Streaming responses](#streaming-responses)
    - [HTTPS server](#https-server)
- [License](#license)

Notice (June 2017)
------------------

[](#notice-june-2017)

This repository is just a prototype and won't be supported anymore. Every feature of this prototype moved to the official [ReactPHP HTTP-Server](https://github.com/reactphp/http).

Usage
-----

[](#usage)

### HttpServer

[](#httpserver)

The HTTP server needs a socket and callback function to work. The socket will be used to communicate between server and client. The callback function is used to react on requests and return responses. The callback function *must* return either a promise or a response object. The `HttpServer` class uses [PSR-7 Middleware](https://packagist.org/packages/ringcentral/psr7) objects. And these need to be used also in the [callback function](#create-a-callback-function).

#### Create a callback function

[](#create-a-callback-function)

The `HttpServer` uses a callback function. This callback function has a request object as its only paremter and expects to return a response object.

Create your own callback function to react on responses as you wish (e.g. check the response, fetch values from the database and send the response). But be careful, blocking operations like database or file operations can lead to a slow down server.

```
$callback = function (ServerRequestInterface $request) {
    $content = '

     Hello World!
     This is your own little server. Written in PHP :-)

';

    return new Response(
        200,
        array(
            'Content-Length' => strlen($content),
            'Content-Type' => 'text/html'
        ),
        $content
    );
};

$socket = new Socket($loop);
$socket->listen(10000, 'localhost');

$server = new HttpServer($socket, $callback);
$loop->run();
```

This example will respond with a simple HTML site on every request send to this server. But this will always send a response to the client as soon the header of the request has arrived at the server. If the request consists of body data, these will be ignored and the TCP connection will be closed as the response is sent to the client. To handle the body data you have to use streams.

Every version after `v0.4.0` will stream requests. This means the body of the request object of your callback function.

Streaming requests makes it possible to send big amount of data in small chunks from the client to the server. E.g you can start the computation of the request, when your application received an specific part of the body.

The body of the request object in your callback and middleware function will be a [ReadableStreamInterface](https://github.com/reactphp/stream).

Every request body stream will send an end event when the stream is successfully completed. We have to use a [promise](https://github.com/reactphp/promise) to ensure that the response only will be send to the client when the request stream is finished.

The next example will do the same as the previous example, but will wait until the request stream will be finished.

```
$callback = function (ServerRequestInterface $request) {
    return new Promise(function ($resolve, $reject) use ($request) {
        $request->getBody->on('end', function () use (&$contentLength, $resolve) {
            $content = '

     Hello World!
     This is your own little server. Written in PHP :-)

';

            return new Response(
                200,
                array(
                    'Content-Length' => strlen($content),
                    'Content-Type' => 'text/html'
                ),
                $content
            );
        });
    };
}
```

The body of the request will always be a [ReactPHP stream](https://github.com/reactphp/stream). The PSR-7 methods of the [StreamInterface](http://www.php-fig.org/psr/psr-7/#streams)are currently not needed and have no function at this point of development, but they may have in the further development.

In the following example a listener will be added to the 'data' event, which will count just the transferred string data length. At the end of the body stream the length of the transferred data will be send in an text via a HTTP response to the client.

```
$callback = function (ServerRequestInterface $request) {
    return new Promise(function ($resolve, $reject) use ($body) {
        $contentLength = 0;
        $request->getBody()->on('data', function ($chunk) use ($resolve, &$contentLength) {
            $contentLength += strlen($chunk);
        });

        $request->getBody()->on('end', function () use (&$contentLength, $resolve) {
            $content = "Transferred data length: " . $contentLength ."\n";
            $resolve(
                new Response(
                    200,
                    array(
                        'Content-Length' => strlen($content),
                        'Content-Type' => 'text/html'
                    ),
                    $content
                )
            );
        });
    });
};
```

This is just an example you can use a [BufferedSink](https://github.com/reactphp/stream) from the `reactphp/stream` to avoid these lines of code.

This example just streams the body of the request. The body of the response can alseo be streamed. Check out the [Streaming responses](#streaming-responses) chapter.

The [ServerRequestInterface](http://www.php-fig.org/psr/psr-7/#server-side-requests) MUST be used as first parameter in the callback and middleware functions. The parameters of the request have the default values defined by the PSR-7 Interface and can be changed by the middleware.

Check out the `examples` folder how your server could look like.

### ChunkedDecoder

[](#chunkeddecoder)

The `ChunkedDecoder` is used to decode the single chunks send by a HTTP request with a `Transfer-Encoding: chunked`. The HTTP server will send the encoded body to the callback function.

This class is based on [ReactPHP streams](https://github.com/reactphp/stream). The `HttpServer` will save the chunks until the body is completed and will forward the decoded request to the callback function.

#### Handling exceptions

[](#handling-exceptions)

The code in the callback function can throw Exceptions, but this shouldn't affect the running server. So every uncaught exception will be caught by the `HttpServer` and a 'HTTP 500 Internal Server Error' response will be send to the client, when an exception occures.

Example:

```
