PHP code example of philharmony / http-message

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

    

philharmony / http-message example snippets


use Philharmony\Http\Message\Uri;
use Philharmony\Http\Message\Request;
use Philharmony\Http\Message\Response;
use Philharmony\Http\Message\ServerRequest;

// Create a URI
$uri = Uri::create('https://api.example.com/users');

// Create a client request
$request = Request::create('GET', $uri);

// Server-side request (incoming HTTP request)
$serverRequest = ServerRequest::make(
    method: 'POST',
    uri: '/users',
    body: '{"name":"John"}',
    headers: ['Content-Type' => 'application/json']
);

// Access parsed body
$data = $serverRequest->getParsedBody();

// Create a response
$response = Response::create(200)
    ->withHeader('Content-Type', 'application/json');

echo $response->getStatusCode(); // 200

use Philharmony\Http\Message\Uri;

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

// Using factory method
$uri = Uri::create('https://github.com');

// From parts (parse_url compatible)
$uri = Uri::fromParts([
    'scheme' => 'https',
    'host' => 'api.example.com',
    'path' => '/v1/users'
]);

use Philharmony\Http\Message\Uri;

// IPv6 host
$uri = Uri::create('http://[2001:db8::1]/api');

// IDN host (automatically normalized)
$uri = Uri::create('https://münich.example');

$baseUri = Uri::create('http://localhost');

$secureUri = $baseUri
    ->withScheme('https')
    ->withPath('/search')
    ->withQuery('q=php+8');

echo $baseUri; // http://localhost
echo $secureUri; // https://localhost/search?q=php+8

// Handles spaces and special characters
$uri = Uri::create('https://example.com')
    ->withPath('/my documents/notes & tasks');
echo $uri->getPath(); // /my%20documents/notes%20%26%20tasks

// Protects already encoded characters (prevents double % encoding)
$uri = $uri->withQuery('search=php%208');
echo $uri->getQuery(); // search=php%208 (NOT search=php%25208)

use Philharmony\Http\Message\Stream;

// Create from string (automatically uses php://memory)
$stream = Stream::create('Body content');

// Create from an existing resource
$resource = fopen('data.txt', 'r+');
$streamFromResource = Stream::create($resource);

// Decorate another PSR-7 Stream
$newStream = Stream::create($streamFromResource);

// Create stream directly from file path
$stream = Stream::createFromFile('document.pdf');

// You can also specify the file mode
$stream = Stream::createFromFile('log.txt', 'a+'); // append mode

// Handle errors gracefully
try {
    $stream = Stream::createFromFile('/path/to/nonexistent.file');
} catch (\RuntimeException $e) {
    echo 'Could not create stream: ' . $e->getMessage();
}

$stream = Stream::create('Philharmony');
$stream->write(' Framework');
$stream->rewind();

echo $stream->getContents(); // Philharmony Framework
echo $stream->getSize(); // 21

use Philharmony\Http\Message\Request;

$request = Request::create(
    'GET',
    'https://api.example.com/users',
    '',
    ['Accept' => 'application/json']
);

if ($request->isSafe()) {
    echo "Safe request (GET, HEAD, OPTIONS)";
}

if ($request->isIdempotent()) {
    echo "Request can be safely repeated";
}

if ($request->isHttps()) {
    echo "Secure request";
}

use Philharmony\Http\Message\ServerRequest;

$serverRequest = ServerRequest::make(
    method: 'POST',
    uri: '/profile/update',
    serverParams: $_SERVER,
    body: '{"name":"Philharmony"}',
    headers: ['Content-Type' => 'application/json'],
    cookieParams: $_COOKIE
);

if ($serverRequest->isJson()) {
    $data = $serverRequest->getParsedBody();
}

if ($serverRequest->isForm()) {
    $form = $serverRequest->getParsedBody();
}

$raw = $serverRequest->getRawBody();

$userId = $serverRequest->input('user.id', 'guest');

if ($serverRequest->has('token')) {
    // token exists
}

use Philharmony\Http\Message\Response;

// Automatically sets "201 Created" reason phrase
$response = Response::create(201); 
echo $response->getReasonPhrase(); // "Created"

// Fluent interface and smart status checks
$errorResponse = $response
    ->withStatus(403)
    ->withHeader('X-Reason', 'Security');

// Powerful status code helpers powered by Philharmony Enums
if ($response->isInformational()) {
    echo "Status is 1xx";
}

if ($response->isSuccessful()) {
    echo "Status is 2xx (Success!)";
}

if ($response->isRedirection()) {
    echo "Status is 3xx (Redirecting...)";
}

if ($response->isClientError()) {
    echo "Status is 4xx (Bad Request, Unauthorized, etc.)";
}

if ($response->isServerError()) {
    echo "Status is 5xx (Server crashed)";
}

if ($response->isError()) {
    echo "Any error occurred (4xx or 5xx)";
}

use Philharmony\Http\Message\UploadedFile;

$file = UploadedFile::create(
    fileOrStream: '/tmp/phpYzdqkD',
    size: 1024,
    errorStatus: UPLOAD_ERR_OK,
    clientFilename: 'avatar.png',
    clientMediaType: 'image/png',
    fullPath: 'users/avatars/avatar.png' // PHP 8.1+ support
);

// Integration with ContentType Enum
if ($file->getContentType()?->isImage()) {
    $file->moveTo('/var/www/uploads/profile.png');
}

use Philharmony\Http\Message\Enum\UploadError;

$error = UploadError::from($file->getError());

if ($error->isError()) {
    echo $error->message();
}