PHP code example of fatcode / http-server

1. Go to this page and download the library: Download fatcode/http-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fatcode / http-server example snippets


 declare(strict_types=1);

use FatCode\HttpServer\HttpServer;
use FatCode\HttpServer\Server\Router;
use FatCode\HttpServer\Response;

// Instantiates router for registering resources:
$router = new Router();
$router->get('/hello', function () {
    return new Response('Hello You!');
});

// Run server at localhost:80
$server = new HttpServer();
$server->use($router);
$server->start();

 declare(strict_types=1);

use FatCode\HttpServer\HttpServer;
use FatCode\HttpServer\Server\HttpServerSettings;

// Setting pid file will make server run as a daemon.
$settings = new HttpServerSettings('0.0.0.0', 8080);
$settings->setPidFile(sys_get_temp_dir() . '/my_pid.pid');

// Note this server will always respond with 404 response, as there is
// no router passed that can handle the request.
$server = new HttpServer();
$server->start();

 declare(strict_types=1);

use FatCode\HttpServer\HttpServer;
use FatCode\HttpServer\Response;
use Psr\Http\Message\ServerRequestInterface;

// Simple pong server.
$server = new HttpServer();
$server->use(function (ServerRequestInterface $request) : Response {
    if ($request->getUri()->getPath() === '/ping') {
        return new Response('Pong!');
    }
    return new Response('Please call /ping uri.');
});
$server->start();

 declare(strict_types=1);

use FatCode\HttpServer\Response;
use FatCode\HttpServer\HttpStatusCode;

// Creates new response with status code 200.
$response = new Response("Hello world!", HttpStatusCode::OK());

 declare(strict_types=1);

use FatCode\HttpServer\HttpServer;
use Psr\Http\Message\ServerRequestInterface;
use FatCode\HttpServer\Response;
use FatCode\HttpServer\Server\Router;

// Initialize router
$router = new Router();

// Register parametrized route
$router->get('/hello/{name}', function (ServerRequestInterface $request) : Response {
    // Return response
    return new Response("Hello, your name is {$request->getAttribute('name')}");
});

// Setup http server
$server = new HttpServer();
$server->use($router);
$server->start();