PHP code example of lighthouse / http

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

    

lighthouse / http example snippets


use Lighthouse\Http\Request;

// Simple request
$request = new Request('GET', 'https://api.example.com/users');

// Request with headers and body
$request = new Request(
    method: 'POST',
    uri: 'https://api.example.com/users',
    headers: [
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
    ],
    body: json_encode(['name' => 'John'])
);

use Lighthouse\Http\ServerRequest;

// Create from PHP superglobals
$request = ServerRequest::fromGlobals();

// Access request data
$method = $request->getMethod();
$path = $request->getUri()->getPath();
$query = $request->getQueryParams();
$body = $request->getParsedBody();

use Lighthouse\Http\Response;

// Simple response
$response = new Response(200);

// Response with body
$response = new Response(
    statusCode: 200,
    headers: ['Content-Type' => 'application/json'],
    body: json_encode(['status' => 'ok'])
);

// Check response status
if ($response->isSuccessful()) {
    // 2xx response
}

use Lighthouse\Http\Stream;

// Create from string
$stream = Stream::create('Hello, World!');

// Create from file
$stream = Stream::createFromFile('/path/to/file.txt', 'r');

// Read and write
$content = $stream->getContents();
$stream->write('more data');

use Lighthouse\Http\Uri;

$uri = new Uri('https://user:[email protected]:8080/path?query=value#fragment');

$scheme = $uri->getScheme();     // 'https'
$host = $uri->getHost();         // 'example.com'
$port = $uri->getPort();         // 8080
$path = $uri->getPath();         // '/path'
$query = $uri->getQuery();       // 'query=value'

// Modify (returns new instance)
$newUri = $uri->withPath('/new-path')->withQuery('new=query');

use Lighthouse\Http\Factory\RequestFactory;
use Lighthouse\Http\Factory\ResponseFactory;
use Lighthouse\Http\Factory\StreamFactory;
use Lighthouse\Http\Factory\UriFactory;

$requestFactory = new RequestFactory();
$request = $requestFactory->createRequest('GET', 'https://example.com');

$responseFactory = new ResponseFactory();
$response = $responseFactory->createResponse(200, 'OK');

$streamFactory = new StreamFactory();
$stream = $streamFactory->createStream('content');

$uriFactory = new UriFactory();
$uri = $uriFactory->createUri('https://example.com');

$request = new Request('GET', 'https://example.com');

// This returns a NEW request - doesn't modify original
$newRequest = $request->withMethod('POST');

$request->getMethod();    // Still 'GET'
$newRequest->getMethod(); // 'POST'