PHP code example of wp-php-toolkit / http-server

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

    

wp-php-toolkit / http-server example snippets



WordPress\HttpServer\TcpServer;
use WordPress\HttpServer\IncomingRequest;
use WordPress\HttpServer\Response\ResponseWriteStream;

$server = new TcpServer( '127.0.0.1', 8080 );

$server->set_handler( function ( IncomingRequest $request, ResponseWriteStream $response ) {
	$response->send_http_code( 200 );
	$response->send_header( 'Content-Type', 'text/plain' );
	$response->append_bytes( "Hello from " . $request->method . " " . $request->url . "\n" );
} );

$server->serve( function ( $host, $port ) {
	echo "Listening on http://{$host}:{$port}\n";
} );


WordPress\HttpServer\TcpServer;
use WordPress\HttpServer\IncomingRequest;
use WordPress\HttpServer\Response\ResponseWriteStream;

$server = new TcpServer( '127.0.0.1', 8080 );

$server->set_handler( function ( IncomingRequest $request, ResponseWriteStream $response ) {
	$path = $request->get_parsed_url()->pathname;

	if ( '/api/status' === $path ) {
		$response->send_http_code( 200 );
		$response->send_header( 'Content-Type', 'application/json' );
		$response->append_bytes( json_encode( array(
			'ok'     => true,
			'pid'    => getmypid(),
			'memory' => memory_get_usage( true ),
		) ) );
		return;
	}

	if ( '/api/echo' === $path && 'POST' === $request->method ) {
		$body = '';
		while ( ! $request->body_stream->reached_end_of_data() ) {
			$n = $request->body_stream->pull( 4096 );
			if ( $n > 0 ) $body .= $request->body_stream->consume( $n );
		}
		$response->send_http_code( 200 );
		$response->send_header( 'Content-Type', 'text/plain' );
		$response->append_bytes( $body );
		return;
	}

	$response->send_http_code( 404 );
	$response->append_bytes( "Not found\n" );
} );

$server->serve();


WordPress\HttpServer\Response\BufferingResponseWriter;

$writer = new BufferingResponseWriter();
$writer->send_http_code( 200 );
$writer->send_header( 'Content-Type', 'text/html' );
$writer->append_bytes( '<!doctype html><title>Hi</title><h1>Hello</h1>' );
$writer->append_bytes( '<p>Buffered body, sent at the end.</p>' );

ob_start();
$writer->close_writing();
$response_body = ob_get_clean();

echo "headers before send:\n";
foreach ( $writer->get_buffered_headers() as $name => $value ) {
	echo "{$name}: {$value}\n";
}
echo "\nbody:\n" . $response_body;