HttpServer component: a simple HTTP Server for your PHP application

Posted by víctor on August 15th, 2014
Photo by Yuri Samoilov

I'm currently working on a built-in server for Spress, a simple HTTP server for watching changes in files without run spress site:build command every time you make a change. HttpServer is a small server built with REACT, the event-driven and non-blocking I/O library for PHP.

The installation is straightforward thanks to Composer tool: add the following to your composer.json file:

"require": {
    "yosymfony/httpserver": "1.0.x-dev"

An example of how to use:

$requestHandler = new RequestHandler(function($request) {
    return 'Hi Yo! Symfony';

$server = new HttpServer($requestHandler);

// go to http://localhost:8080

RequestHandler let you configure params such as port or host for managing requests. The constructor only expects a single callable type argument. That is a function to handle each request.

The handler function

The handler function receives a single parameter to describe the request. By default, this argument is a object type React\Http\Request. If you want to receive a Symfony HttpFoundation Request object, you need to enable this mode: $requestHandler->enableHttpFoundationRequest().

Configuring the response

By default, the Content-Type value is text/plain at the response header and a simple return 'your text'; works fine but you can customize your response with status code and custom headers attributes.

A complete example

This example point out how to use an array response:

include_once __DIR__ . '/vendor/autoload.php';

use Yosymfony\HttpServer\HttpServer;
use Yosymfony\HttpServer\RequestHandler;

$requestHandler = new RequestHandler(function($request) {
   return [
      'content' => '<?xml version="1.0" encoding="UTF-8"?><root>Hi</root>',
      'headers' => ['Content-Type' => 'text/xml'],
      'status_code' => 200


$server = new HttpServer($requestHandler);

Nice coding ;)


comments powered by Disqus