PHP code example of jasny / http-message

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

    

jasny / http-message example snippets


$request = (new Jasny\HttpMessage\ServerRequest())->withGlobalEnvironment();

use Jasny\HttpMessage\ServerRequest;

// $_GET is not affected
$requestByVal = (new ServerRequest())->withGlobalEnvironment();
$requestByVal = $request->withQueryParams(['foo' => 1]);
var_dump($_GET); // array(0) { }

// $_GET is affected
$requestByRef = (new ServerRequest())->withGlobalEnvironment(true);
$requestByRef = $request->withQueryParams(['foo' => 1]);
var_dump($_GET); // array(1) { ["foo"]=> int(1) }

$response = new Jasny\HttpMessage\Response();

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\Response;

$request = (new ServerRequest())->withGlobalEnvironment();
$response = $router->handle($request, new Response());

$response->emit();

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\Response;
use Jasny\HttpMessage\Emitter;

$request = (new ServerRequest())->withGlobalEnvironment();
$response = $router->handle($request, new Response());

$emitter = new Emitter();
$emitter->emit($response);

$request = (new Response())->withGlobalEnvironment(true);
$request->withHeader('Content-Type', 'text/plain'); // Does `header("Content-Type: text/plain")`
$request->getBody()->write('hello world');          // Outputs "hello world"

$uri = new Jasny\HttpMessage\Uri("http://www.example.com/foo");

$input = new Jasny\HttpMessage\Stream();
$input->write(json_encode(['foo' => 'bar', 'color' => 'red']));

$handle = fopen('php://memory', 'r+');
$stream = new Jasny\HttpMessage\Stream($handle);

$newResponse = $response->withBody(clone $response->getBody());

use Jasny\HttpMessage\ServerRequest;

$request = (new ServerRequest())->withAttribute('accept_json', function(ServerRequest $request) {
    $accept = $request->getHeaderLine('Accept');
    return strpos($accept, 'application/json') !== false || strpos($accept, '*/*') !== false;
});

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\DerivedAttributeInterface;

class DetectBot implements DerivedAttributeInterface
{
    public static $identifiers = [
        'google' => 'googlebot',
        'yahoo' => 'yahoobot',
        'magpie' => 'magpie-crawler'
    ];

    protected $detect = [];
    
    public function __construct(array $detect)
    {
        $this->detect = $detect;
    }

    public function __invoke(ServerRequest $request)
    {
        $useragent = $request->getHeaderLine('User-Agent');
        $detected = false;

        foreach ($this->detect as $bot) {
            $identifier = static::$identifiers[$bot];
            $detected = $detected || stripos($useragent, $bot) !== false;
        }

        return $detected;
    }
}

$request = (new ServerRequest())
    ->withAttribute('is_friendly_bot', new DetectBot(['google', 'yahoo']))
    ->withAttribute('is_annoying_bot', new DetectBot(['magpie']));

use Jasny\HttpMessage\ServerRequest;

$request = (new ServerRequest())->withGlobalEnvironment();
$request->getAttribute('client_ip'); // always returns $_SERVER['REMOTE_ADDR']

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\DerivedAttribute\ClientIp;

$request = (new ServerRequest())
    ->withGlobalEnvironment()
    ->withAttribute('client_ip', new ClientIp(['trusted_proxy => '10.0.0.0/24']);

$ip = $request->getAttribute('client_ip'); // for a request from the internal network, use the `X-Forwarded-For` header

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\DerivedAttribute\ClientIp;

$request = (new ServerRequest())
    ->withGlobalEnvironment()
    ->withoutHeader('Client-Ip')
    ->withoutHeader('Forwarded')
    ->withAttribute('client_ip', new ClientIp(['trusted_proxy' => '10.0.0.0/24']);

use Jasny\HttpMessage\ServerRequest;

$request = (new ServerRequest())->withGlobalEnvironment();
$isXhr = $request->getAttribute('is_xhr'); // true or false

use Jasny\HttpMessage\ServerRequest;

$request = (new ServerRequest())->withGlobalEnvironment();
$back = $request->getAttribute('local_referer') ?: '/'; // Referer Uri path, defaults to `/` for no or external referer

use Jasny\HttpMessage\ServerRequest;
use Jasny\HttpMessage\DerivedAttribute\LocalReferer;

$request = (new ServerRequest())
    ->withGlobalEnvironment()
    ->withAttribute('local_referer', new LocalReferer(['checkScheme' => false, 'checkPort' => false]));

$request = (new ServerRequest())
    ->withMethod('GET')
    ->withUri('/foo')
    ->withQueryParams(['page' => 1]);

// Start output buffering, so the output isn't send directly
ob_start();

// Create server request that is bound to the global enviroment.
$baseRequest = (new ServerRequest())->withGlobalEnvironment(true);

// Modifying the bound request, modifies the superglobals.
$request = $baseRequest
    ->withServerParams(['REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/foo'])
    ->withQueryParams(['page' => 1]);

// Create response that is bound to the global enviroment.
$baseResponse = (new Response())->withGlobalEnvironment(true);

// Some PSR-7 compatible router handles the request. The code uses `header` and `echo` to output.
$router->handle($request, $baseResponse);

// Disconnect the global environment, copy the data and headers
$response = $response->withoutGlobalEnvironment();

// Refiving the base request and response, restores the global environment. Also clean the output buffer.
$baseRequest = $baseRequest->revive();
$baseResponse = $baseResponse->revive()->withBody(new OutputBufferStream());

// Assert response
...

// Ready for next request :)

function errorHandlerMiddleware(ServerRequestInterface $request, ResponseInterface $response, $next) {
    try {
        $newResponse = $next($request, $response);
    } catch (Throwable $error) {
        // If the next middleware or controller has done something like set the response status, the response is stale.
        
        if ($request instanceof Jasny\HttpMessage\ServerRequest) {
            $request = $request->revive();
        }
        
        if ($response instanceof Jasny\HttpMessage\Response) {
            $response = $response->revive();
        }

        $newResponse = handleError($request, $response, $error);
    }

    return $newResponse;
}

$stream = Jasny\HttpMessage\Stream::open('php://memory', 'r+');