PHP code example of wayn3r / php-server

1. Go to this page and download the library: Download wayn3r/php-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/ */

    

wayn3r / php-server example snippets




= \Http\Server::getServer();

$app->get('/', 
    function(\Http\Request $req, \Http\Response $res){
        $res->send('Hello world');
    }
);

$app->start();


php -S localhost:8080 -c php.ini index.php



$router = new \Http\Router;

$router->get('/', function(\Http\Request $req, \Http\Response $res){
    $res->json([
        'message' => 'Hello world from user router'
    ]);
});

return $router;



Router = erver::getServer();

$app->use('/user', $userRouter);

$app->start();




$router = new \Http\Router;

$router->get('/', function(\Http\Request $req, \Http\Response $res){
    $query = $req->query();
    $body = $req->body();
    $res->json([
        'query' => $query,
        'body' => $body
    ]);
});

return $router;



$router = new \Http\Router;

$router->get('/:id', function(\Http\Request $req, \Http\Response $res){
    ['id' => $id] = $req->params();
    $query = $req->query();
    $body = $req->body();
    $res->json([
        'query' => $query,
        'body' => $body,
        'id' => $id
    ]);
});

return $router;



$router = new \Http\Router;

$router->get('/', function(\Http\Request $req, \Http\Response $res, callable $next){
    $id = $req->query()['id'];
    if(!$id) return $next('El parametro id es requerido');
    $res->json([
        'id' => $id
    ]);
});

$router->post('/', function(\Http\Request $req, \Http\Response $res, callable $next){
    $name = $req->query()['name'];
    if(!$name) return $next('El parametro name es requerido');
    $res->json([
        'name' => $name
    ]);
});

$router->use('/', function($errors, $_, \Http\Response $res){
    $res->status(400)->json([
        'error' => $errors
    ]);
});

return $router;



$router = new \Http\Router;

$router->get('/', 
    function(\Http\Request $req, \Http\Response $res, callable $next){
        $id = $req->query()['id'];
        if(!$id || !is_numeric($id)) 
            return $res->status(400)->json([
                'error' => 'ID invalido'
            ]); 
        $req->id = intval($id);
        $next();
    },
    function(\Http\Request $req, \Http\Response $res){
        $id = $req->id;
        $res->json([
            'id' => $id
        ]);
    }
);

return $router;




$router = new \Http\Router;

$validator = new \Validate\Validator;

$router->get('/', 
    $validator->>query()['id']);
        $res->json([
            'id' => $id
        ]);
    }
);

return $router;