PSR-7 HTTP message library

Related tags

Frameworks psr7
Overview

PSR-7 Message Implementation

This repository contains a full PSR-7 message implementation, several stream decorators, and some helpful functionality like query string parsing.

CI Static analysis

Stream implementation

This package comes with a number of stream implementations and stream decorators.

AppendStream

GuzzleHttp\Psr7\AppendStream

Reads from multiple streams, one after the other.

use GuzzleHttp\Psr7;

$a = Psr7\Utils::streamFor('abc, ');
$b = Psr7\Utils::streamFor('123.');
$composed = new Psr7\AppendStream([$a, $b]);

$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));

echo $composed; // abc, 123. Above all listen to me.

BufferStream

GuzzleHttp\Psr7\BufferStream

Provides a buffer stream that can be written to fill a buffer, and read from to remove bytes from the buffer.

This stream returns a "hwm" metadata value that tells upstream consumers what the configured high water mark of the stream is, or the maximum preferred size of the buffer.

use GuzzleHttp\Psr7;

// When more than 1024 bytes are in the buffer, it will begin returning
// false to writes. This is an indication that writers should slow down.
$buffer = new Psr7\BufferStream(1024);

CachingStream

The CachingStream is used to allow seeking over previously read bytes on non-seekable streams. This can be useful when transferring a non-seekable entity body fails due to needing to rewind the stream (for example, resulting from a redirect). Data that is read from the remote stream will be buffered in a PHP temp stream so that previously read bytes are cached first in memory, then on disk.

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
$stream = new Psr7\CachingStream($original);

$stream->read(1024);
echo $stream->tell();
// 1024

$stream->seek(0);
echo $stream->tell();
// 0

DroppingStream

GuzzleHttp\Psr7\DroppingStream

Stream decorator that begins dropping data once the size of the underlying stream becomes too full.

use GuzzleHttp\Psr7;

// Create an empty stream
$stream = Psr7\Utils::streamFor();

// Start dropping data when the stream has more than 10 bytes
$dropping = new Psr7\DroppingStream($stream, 10);

$dropping->write('01234567890123456789');
echo $stream; // 0123456789

FnStream

GuzzleHttp\Psr7\FnStream

Compose stream implementations based on a hash of functions.

Allows for easy testing and extension of a provided stream without needing to create a concrete class for a simple extension point.

use GuzzleHttp\Psr7;

$stream = Psr7\Utils::streamFor('hi');
$fnStream = Psr7\FnStream::decorate($stream, [
    'rewind' => function () use ($stream) {
        echo 'About to rewind - ';
        $stream->rewind();
        echo 'rewound!';
    }
]);

$fnStream->rewind();
// Outputs: About to rewind - rewound!

InflateStream

GuzzleHttp\Psr7\InflateStream

Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content.

This stream decorator converts the provided stream to a PHP stream resource, then appends the zlib.inflate filter. The stream is then converted back to a Guzzle stream resource to be used as a Guzzle stream.

LazyOpenStream

GuzzleHttp\Psr7\LazyOpenStream

Lazily reads or writes to a file that is opened only after an IO operation take place on the stream.

use GuzzleHttp\Psr7;

$stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
// The file has not yet been opened...

echo $stream->read(10);
// The file is opened and read from only when needed.

LimitStream

GuzzleHttp\Psr7\LimitStream

LimitStream can be used to read a subset or slice of an existing stream object. This can be useful for breaking a large file into smaller pieces to be sent in chunks (e.g. Amazon S3's multipart upload API).

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
echo $original->getSize();
// >>> 1048576

// Limit the size of the body to 1024 bytes and start reading from byte 2048
$stream = new Psr7\LimitStream($original, 1024, 2048);
echo $stream->getSize();
// >>> 1024
echo $stream->tell();
// >>> 0

MultipartStream

GuzzleHttp\Psr7\MultipartStream

Stream that when read returns bytes for a streaming multipart or multipart/form-data stream.

NoSeekStream

GuzzleHttp\Psr7\NoSeekStream

NoSeekStream wraps a stream and does not allow seeking.

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor('foo');
$noSeek = new Psr7\NoSeekStream($original);

echo $noSeek->read(3);
// foo
var_export($noSeek->isSeekable());
// false
$noSeek->seek(0);
var_export($noSeek->read(3));
// NULL

PumpStream

GuzzleHttp\Psr7\PumpStream

Provides a read only stream that pumps data from a PHP callable.

When invoking the provided callable, the PumpStream will pass the amount of data requested to read to the callable. The callable can choose to ignore this value and return fewer or more bytes than requested. Any extra data returned by the provided callable is buffered internally until drained using the read() function of the PumpStream. The provided callable MUST return false when there is no more data to read.

Implementing stream decorators

Creating a stream decorator is very easy thanks to the GuzzleHttp\Psr7\StreamDecoratorTrait. This trait provides methods that implement Psr\Http\Message\StreamInterface by proxying to an underlying stream. Just use the StreamDecoratorTrait and implement your custom methods.

For example, let's say we wanted to call a specific function each time the last byte is read from a stream. This could be implemented by overriding the read() method.

use Psr\Http\Message\StreamInterface;
use GuzzleHttp\Psr7\StreamDecoratorTrait;

class EofCallbackStream implements StreamInterface
{
    use StreamDecoratorTrait;

    private $callback;

    public function __construct(StreamInterface $stream, callable $cb)
    {
        $this->stream = $stream;
        $this->callback = $cb;
    }

    public function read($length)
    {
        $result = $this->stream->read($length);

        // Invoke the callback when EOF is hit.
        if ($this->eof()) {
            call_user_func($this->callback);
        }

        return $result;
    }
}

This decorator could be added to any existing stream and used like so:

seek(0); $eofStream->read(3); // echoes "EOF!" ">
use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor('foo');

$eofStream = new EofCallbackStream($original, function () {
    echo 'EOF!';
});

$eofStream->read(2);
$eofStream->read(1);
// echoes "EOF!"
$eofStream->seek(0);
$eofStream->read(3);
// echoes "EOF!"

PHP StreamWrapper

You can use the GuzzleHttp\Psr7\StreamWrapper class if you need to use a PSR-7 stream as a PHP stream resource.

Use the GuzzleHttp\Psr7\StreamWrapper::getResource() method to create a PHP stream from a PSR-7 stream.

use GuzzleHttp\Psr7\StreamWrapper;

$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
$resource = StreamWrapper::getResource($stream);
echo fread($resource, 6); // outputs hello!

Static API

There are various static methods available under the GuzzleHttp\Psr7 namespace.

GuzzleHttp\Psr7\Message::toString

public static function toString(MessageInterface $message): string

Returns the string representation of an HTTP message.

$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
echo GuzzleHttp\Psr7\Message::toString($request);

GuzzleHttp\Psr7\Message::bodySummary

public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null

Get a short summary of the message body.

Will return null if the response is not printable.

GuzzleHttp\Psr7\Message::rewindBody

public static function rewindBody(MessageInterface $message): void

Attempts to rewind a message body and throws an exception on failure.

The body of the message will only be rewound if a call to tell() returns a value other than 0.

GuzzleHttp\Psr7\Message::parseMessage

public static function parseMessage(string $message): array

Parses an HTTP message into an associative array.

The array contains the "start-line" key containing the start line of the message, "headers" key containing an associative array of header array values, and a "body" key containing the body of the message.

GuzzleHttp\Psr7\Message::parseRequestUri

public static function parseRequestUri(string $path, array $headers): string

Constructs a URI for an HTTP request message.

GuzzleHttp\Psr7\Message::parseRequest

public static function parseRequest(string $message): Request

Parses a request message string into a request object.

GuzzleHttp\Psr7\Message::parseResponse

public static function parseResponse(string $message): Response

Parses a response message string into a response object.

GuzzleHttp\Psr7\Header::parse

public static function parse(string|array $header): array

Parse an array of header values containing ";" separated data into an array of associative arrays representing the header key value pair data of the header. When a parameter does not contain a value, but just contains a key, this function will inject a key with a '' string value.

GuzzleHttp\Psr7\Header::normalize

public static function normalize(string|array $header): array

Converts an array of header values that may contain comma separated headers into an array of headers with no comma separated values.

GuzzleHttp\Psr7\Query::parse

public static function parse(string $str, int|bool $urlEncoding = true): array

Parse a query string into an associative array.

If multiple values are found for the same key, the value of that key value pair will become an array. This function does not parse nested PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will be parsed into ['foo[a]' => '1', 'foo[b]' => '2']).

GuzzleHttp\Psr7\Query::build

public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string

Build a query string from an array of key value pairs.

This function can use the return value of parse() to build a query string. This function does not modify the provided keys when an array is encountered (like http_build_query() would).

GuzzleHttp\Psr7\Utils::caselessRemove

public static function caselessRemove(iterable $keys, $keys, array $data): array

Remove the items given by the keys, case insensitively from the data.

GuzzleHttp\Psr7\Utils::copyToStream

public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void

Copy the contents of a stream into another stream until the given number of bytes have been read.

GuzzleHttp\Psr7\Utils::copyToString

public static function copyToString(StreamInterface $stream, int $maxLen = -1): string

Copy the contents of a stream into a string until the given number of bytes have been read.

GuzzleHttp\Psr7\Utils::hash

public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string

Calculate a hash of a stream.

This method reads the entire stream to calculate a rolling hash, based on PHP's hash_init functions.

GuzzleHttp\Psr7\Utils::modifyRequest

public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface

Clone and modify a request with the given changes.

This method is useful for reducing the number of clones needed to mutate a message.

  • method: (string) Changes the HTTP method.
  • set_headers: (array) Sets the given headers.
  • remove_headers: (array) Remove the given headers.
  • body: (mixed) Sets the given body.
  • uri: (UriInterface) Set the URI.
  • query: (string) Set the query string value of the URI.
  • version: (string) Set the protocol version.

GuzzleHttp\Psr7\Utils::readLine

public static function readLine(StreamInterface $stream, int $maxLength = null): string

Read a line from the stream up to the maximum allowed buffer length.

GuzzleHttp\Psr7\Utils::streamFor

public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface

Create a new stream based on the input type.

Options is an associative array that can contain the following keys:

  • metadata: Array of custom metadata.
  • size: Size of the stream.

This method accepts the following $resource types:

  • Psr\Http\Message\StreamInterface: Returns the value as-is.
  • string: Creates a stream object that uses the given string as the contents.
  • resource: Creates a stream object that wraps the given PHP stream resource.
  • Iterator: If the provided value implements Iterator, then a read-only stream object will be created that wraps the given iterable. Each time the stream is read from, data from the iterator will fill a buffer and will be continuously called until the buffer is equal to the requested read size. Subsequent read calls will first read from the buffer and then call next on the underlying iterator until it is exhausted.
  • object with __toString(): If the object has the __toString() method, the object will be cast to a string and then a stream will be returned that uses the string value.
  • NULL: When null is passed, an empty stream object is returned.
  • callable When a callable is passed, a read-only stream object will be created that invokes the given callable. The callable is invoked with the number of suggested bytes to read. The callable can return any number of bytes, but MUST return false when there is no more data to return. The stream object that wraps the callable will invoke the callable until the number of requested bytes are available. Any additional bytes will be buffered and used in subsequent reads.
$stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));

$generator = function ($bytes) {
    for ($i = 0; $i < $bytes; $i++) {
        yield ' ';
    }
}

$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));

GuzzleHttp\Psr7\Utils::tryFopen

public static function tryFopen(string $filename, string $mode): resource

Safely opens a PHP stream resource using a filename.

When fopen fails, PHP normally raises a warning. This function adds an error handler that checks for errors and throws an exception instead.

GuzzleHttp\Psr7\Utils::uriFor

public static function uriFor(string|UriInterface $uri): UriInterface

Returns a UriInterface for the given value.

This function accepts a string or UriInterface and returns a UriInterface for the given value. If the value is already a UriInterface, it is returned as-is.

GuzzleHttp\Psr7\MimeType::fromFilename

public static function fromFilename(string $filename): string|null

Determines the mimetype of a file by looking at its extension.

GuzzleHttp\Psr7\MimeType::fromExtension

public static function fromExtension(string $extension): string|null

Maps a file extensions to a mimetype.

Upgrading from Function API

The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience:

Original Function Replacement Method
str Message::toString
uri_for Utils::uriFor
stream_for Utils::streamFor
parse_header Header::parse
normalize_header Header::normalize
modify_request Utils::modifyRequest
rewind_body Message::rewindBody
try_fopen Utils::tryFopen
copy_to_string Utils::copyToString
copy_to_stream Utils::copyToStream
hash Utils::hash
readline Utils::readLine
parse_request Message::parseRequest
parse_response Message::parseResponse
parse_query Query::parse
build_query Query::build
mimetype_from_filename MimeType::fromFilename
mimetype_from_extension MimeType::fromExtension
_parse_message Message::parseMessage
_parse_request_uri Message::parseRequestUri
get_message_body_summary Message::bodySummary
_caseless_remove Utils::caselessRemove

Additional URI Methods

Aside from the standard Psr\Http\Message\UriInterface implementation in form of the GuzzleHttp\Psr7\Uri class, this library also provides additional functionality when working with URIs as static methods.

URI Types

An instance of Psr\Http\Message\UriInterface can either be an absolute URI or a relative reference. An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, the base URI. Relative references can be divided into several forms according to RFC 3986 Section 4.2:

  • network-path references, e.g. //example.com/path
  • absolute-path references, e.g. /path
  • relative-path references, e.g. subpath

The following methods can be used to identify the type of the URI.

GuzzleHttp\Psr7\Uri::isAbsolute

public static function isAbsolute(UriInterface $uri): bool

Whether the URI is absolute, i.e. it has a scheme.

GuzzleHttp\Psr7\Uri::isNetworkPathReference

public static function isNetworkPathReference(UriInterface $uri): bool

Whether the URI is a network-path reference. A relative reference that begins with two slash characters is termed an network-path reference.

GuzzleHttp\Psr7\Uri::isAbsolutePathReference

public static function isAbsolutePathReference(UriInterface $uri): bool

Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is termed an absolute-path reference.

GuzzleHttp\Psr7\Uri::isRelativePathReference

public static function isRelativePathReference(UriInterface $uri): bool

Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is termed a relative-path reference.

GuzzleHttp\Psr7\Uri::isSameDocumentReference

public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool

Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its fragment component, identical to the base URI. When no base URI is given, only an empty URI reference (apart from its fragment) is considered a same-document reference.

URI Components

Additional methods to work with URI components.

GuzzleHttp\Psr7\Uri::isDefaultPort

public static function isDefaultPort(UriInterface $uri): bool

Whether the URI has the default port of the current scheme. Psr\Http\Message\UriInterface::getPort may return null or the standard port. This method can be used independently of the implementation.

GuzzleHttp\Psr7\Uri::composeComponents

public static function composeComponents($scheme, $authority, $path, $query, $fragment): string

Composes a URI reference string from its various components according to RFC 3986 Section 5.3. Usually this method does not need to be called manually but instead is used indirectly via Psr\Http\Message\UriInterface::__toString.

GuzzleHttp\Psr7\Uri::fromParts

public static function fromParts(array $parts): UriInterface

Creates a URI from a hash of parse_url components.

GuzzleHttp\Psr7\Uri::withQueryValue

public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface

Creates a new URI with a specific query string value. Any existing query string values that exactly match the provided key are removed and replaced with the given key value pair. A value of null will set the query string key without a value, e.g. "key" instead of "key=value".

GuzzleHttp\Psr7\Uri::withQueryValues

public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface

Creates a new URI with multiple query string values. It has the same behavior as withQueryValue() but for an associative array of key => value.

GuzzleHttp\Psr7\Uri::withoutQueryValue

public static function withoutQueryValue(UriInterface $uri, $key): UriInterface

Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the provided key are removed.

Reference Resolution

GuzzleHttp\Psr7\UriResolver provides methods to resolve a URI reference in the context of a base URI according to RFC 3986 Section 5. This is for example also what web browsers do when resolving a link in a website based on the current request URI.

GuzzleHttp\Psr7\UriResolver::resolve

public static function resolve(UriInterface $base, UriInterface $rel): UriInterface

Converts the relative URI into a new URI that is resolved against the base URI.

GuzzleHttp\Psr7\UriResolver::removeDotSegments

public static function removeDotSegments(string $path): string

Removes dot segments from a path and returns the new path according to RFC 3986 Section 5.2.4.

GuzzleHttp\Psr7\UriResolver::relativize

public static function relativize(UriInterface $base, UriInterface $target): UriInterface

Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():

(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))

One use-case is to use the current request URI as base URI and then generate relative links in your documents to reduce the document size or offer self-contained downloadable document archives.

$base = new Uri('http://example.com/a/b/');
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c'));  // prints 'c'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y'));  // prints '../x/y'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
echo UriResolver::relativize($base, new Uri('http://example.org/a/b/'));   // prints '//example.org/a/b/'.

Normalization and Comparison

GuzzleHttp\Psr7\UriNormalizer provides methods to normalize and compare URIs according to RFC 3986 Section 6.

GuzzleHttp\Psr7\UriNormalizer::normalize

public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface

Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. This methods adds additional normalizations that can be configured with the $flags parameter which is a bitmask of normalizations to apply. The following normalizations are available:

  • UriNormalizer::PRESERVING_NORMALIZATIONS

    Default normalizations which only include the ones that preserve semantics.

  • UriNormalizer::CAPITALIZE_PERCENT_ENCODING

    All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.

    Example: http://example.org/a%c2%b1bhttp://example.org/a%C2%B1b

  • UriNormalizer::DECODE_UNRESERVED_CHARACTERS

    Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.

    Example: http://example.org/%7Eusern%61me/http://example.org/~username/

  • UriNormalizer::CONVERT_EMPTY_PATH

    Converts the empty path to "/" for http and https URIs.

    Example: http://example.orghttp://example.org/

  • UriNormalizer::REMOVE_DEFAULT_HOST

    Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host "localhost". All of file:/myfile, file:///myfile, and file://localhost/myfile are equivalent according to RFC 3986.

    Example: file://localhost/myfilefile:///myfile

  • UriNormalizer::REMOVE_DEFAULT_PORT

    Removes the default port of the given URI scheme from the URI.

    Example: http://example.org:80/http://example.org/

  • UriNormalizer::REMOVE_DOT_SEGMENTS

    Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would change the semantics of the URI reference.

    Example: http://example.org/../a/b/../c/./d.htmlhttp://example.org/a/c/d.html

  • UriNormalizer::REMOVE_DUPLICATE_SLASHES

    Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization may change the semantics. Encoded slashes (%2F) are not removed.

    Example: http://example.org//foo///bar.htmlhttp://example.org/foo/bar.html

  • UriNormalizer::SORT_QUERY_PARAMETERS

    Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be significant (this is not defined by the standard). So this normalization is not safe and may change the semantics of the URI.

    Example: ?lang=en&article=fred?article=fred&lang=en

GuzzleHttp\Psr7\UriNormalizer::isEquivalent

public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool

Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also accepts relative URI references and returns true when they are equivalent. This of course assumes they will be resolved against the same base URI. If this is not the case, determination of equivalence or difference of relative references does not mean anything.

Security

If you discover a security vulnerability within this package, please send an email to [email protected]. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see Security Policy for more information.

License

Guzzle is made available under the MIT License (MIT). Please see License File for more information.

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • Merge current 1.x release into master

    Merge current 1.x release into master

    I've run into a blocker for us in issue #327 and thought I'd just go through the code and create a merge. This merges #345 and #347 so 2.x branch is up-to-date.

    Hopefully this will unblock a 2.x release, since Drupal is waiting for this and out package swisnl/json-api-client.

    opened by bbrala 23
  • Rely on `@deprecated` annotation instead of triggering and immediately silencing a deprecation notice

    Rely on `@deprecated` annotation instead of triggering and immediately silencing a deprecation notice

    There are two static methods in GuzzleHttp\Psr7\Uri that always trigger immediately silenced errors. This introduces a runtime performance penalty to communicate the same information as the already-present @deprecated annotation, which is used by IDEs and static analysis tools to notify developers at dev time that a deprecated method is being used.

    I've received multiple reports of the silenced trigger_error call causing errors in production for users who define custom error handlers, e.g. https://github.com/aws/aws-sdk-php/issues/1198

    /cc @mtdowling @Tobion

    opened by jeskew 23
  • ServerRequest and UploadedFIle Implementation

    ServerRequest and UploadedFIle Implementation

    This is an implementation of ServerRequest and UploadedFIle and closes https://github.com/guzzle/psr7/issues/13.

    I realize there is already a PR for that (https://github.com/guzzle/psr7/pull/32) but it seams sort-of abandoned. I was waiting on that functionality as I need it in one of my projects, so seeing this PR stagnate I decided to reimplement it myself. It has almost full test coverage, the $_FILES array conversion handles more cases, the moveTo method is according to spec and I try to use the already available functionality as much as possible

    Merry Christmas :christmas_tree: :)

    opened by ivank 23
  • PSR-17 stable release

    PSR-17 stable release

    In composer.json this library claims to provide psr/http-factory-implementation. However this is only true for the master branch and the implementation isn't available in any stable release.

    Do you have any ETA when a stable PSR-17 implementation might be available? If not can you recommend me some other library which I could use in the meantime?

    opened by enumag 22
  • fix: seek stream cloned from php input to begining

    fix: seek stream cloned from php input to begining

    Request created from globals always return empty string as a body.

    to test it try create run the following code:

    $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
    var_dump($request->getBody()->getContents());
    

    and do a POST request with non empty body.

    Unfortunately I did not find the way to create a unit test for that case because of this condition:

    \stream_get_meta_data($resource)['uri'] === 'php://input'
    

    there is no way to create a mock of $resource

    opened by hutnikau 17
  • Urgent - v2.1.1 - MessageTrait assertValue broken

    Urgent - v2.1.1 - MessageTrait assertValue broken

    PHP version: 7.4.27 (hint: php --version)

    Description I updated my dependencies, and guzzlehttp/psr7 was updated to v2.1.1. This broke an integration with a third party API that I'm working with. (Largest credit card payment processor in Scandiavia).

    I have traced it down to the changes introduced in MessageTrait for the method assertValue. When the response (which I am not in control over), contains the following header, I get an InvalidArgumentException XXX is not a valid header value.

    X-Iinfo: 12-34567890-123456789 AAAA BC(12 34 5) DE(1234567890123 123) a(1 2 3 4) b(1 2) A1
    

    I have changed the actual values from the header, as I'm not sure if it contains confidential information. The relevant part here is the whitespaces, which failes the parsing introduced in 2.1.1.

    How to reproduce Add the above header to a response.

    Possible Solution Revert the changes done in 2.1.1 back to the behavior in 2.1.0

    Additional context

    opened by thomas-alrek 16
  • Add support SOH symbol to assert of MessageTrait

    Add support SOH symbol to assert of MessageTrait

    I noticed quite common behaviour as described in commentary https://github.com/guzzle/psr7/issues/489#issuecomment-1080758509

    But I noticed that in my googleAnalytics cookie exists SOH symbol which is not allowed with current regular expression

    opened by bullder 15
  • Make more classes final

    Make more classes final

    #286 got closed, but I think we can make a couple more classes final. Since this package implements the PSR-7 standard, I think those implementations should also be final.

    opened by sagikazarmark 15
  • PHP 5.3 Compatibility

    PHP 5.3 Compatibility

    What has been changed:

    • [] arrays were replaced with array()
    • traits were replaced with abstract classes
    • 3 tests in UriTest were updated due to inconsistency in function parse_url before version 5.4.7 and after (but I think it's not a big deal)
    • couple of callable declarations were removed from code (they still exist in phpdoc)
    • 1 test was removed -- BadStream

    No major changes, all tests are feeling good, tested under PHP 5.3.29.

    opened by kirill-konshin 15
  • __toString functions must catch also throwables

    __toString functions must catch also throwables

    On StreamDecoratorTrait I saw a comment about this bug

    I made a test and I saw that the same error is raised with throwables as well..

    My test:

    class MyClass
    {
        public function __toString()
        {
            try {
                throw new Error('whatever');
            } catch (Exception $e) {
                return '';
            }
        }
    }
    
    
    $c = new MyClass();
    (string)$c;
    

    Result: Method MyClass::__toString() must not throw an exception, caught Error: whatever .... ... ...

    Important not sure if FnStream should also have a try..catch. At the moment it does not.

    opened by gmponos 14
  • Exception handling on invalid URI modifications is a breaking change

    Exception handling on invalid URI modifications is a breaking change

    I know that the Guzzle project doesn't state that it is following SemVer, and the release notes clearly say:

    • Ensure each URI modification results in a valid URI according to PSR-7 discussions. Invalid modifications will throw an exception instead of returning a wrong URI or doing some magic.
      • (new Uri)->withPath('foo')->withHost('example.com') will throw an exception because the path of a URI with an authority must start with a slash "/" or be empty

    but I just wanted to give a notice that this change break projects that currently use invalid modifications (as it happened with some of mine, shame on me 🙂), in case that the usual "the app doesn't work anymore" bug report is brought to project maintainers. In my case, I had this code at a few places:

    $uri = new Uri('http://domain.tld')->withPath('path/to/location');
    

    This also affects projects that require guzzlehttp/guzzle, which specifies guzzlehttp/psr7: ^1.3.1 as a dependency.

    :octocat:

    opened by jeromegamez 14
  • Prevent possible warnings on unset variables

    Prevent possible warnings on unset variables

    PHP version: 8.0

    Problem Our server supplies the following value in $_FILES

    {
        "files": {
             "tmp_name":["\/tmp\/upload-file-h1gjcc"],
             "name":["file.pdf"]
        }
    }
    

    Causing warnings such as:

    PHP Warning: Undefined array key "size" in /srv/vendor/guzzlehttp/psr7/src/ServerRequest.php on line 147
    PHP Warning: Trying to access array offset on value of type null in /srv/vendor/guzzlehttp/psr7/src/ServerRequest.php on line 147
    PHP Warning: Undefined array key "error" in /srv/vendor/guzzlehttp/psr7/src/ServerRequest.php on line 148
    PHP Warning: Trying to access array offset on value of type null in /srv/vendor/guzzlehttp/psr7/src/ServerRequest.php on line 148
    
    opened by sudo-plz 0
  • Error when $version parameter is null in Message:parseRequest

    Error when $version parameter is null in Message:parseRequest

    PHP version: 7.4

    Description Problem while implementing websocket server with ratchetphp/Ratchet

    When sending HTTP request headers to Telnet, If '/' is missing from GET HTTP/1.1 An error has occurred.

    An error occurs when creating GuzzleHttp\Psr7\Request instance in Message:parseRequest if the version parameter is null

    PHP Fatal error:  Uncaught TypeError: GuzzleHttp\Psr7\Request::__construct(): Argument #5 ($version) must be of type string, null given, ...
    /guzzlehttp/psr7/src/Request.php:35
    

    How to reproduce

    
    /**
         * Parses a request message string into a request object.
         *
         * @param string $message Request message string.
         */
        public static function parseRequest(string $message): RequestInterface
        {
            $data = self::parseMessage($message);
            $matches = [];
            if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
                throw new \InvalidArgumentException('Invalid request string');
            }
            $parts = explode(' ', $data['start-line'], 3);
            $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
    
            $request = new Request(
                $parts[0],
                $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
                $data['headers'],
                $data['body'],
                $version
            );
    
            return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
        }
    

    Possible Solution In Message::parseRequest, the $version parameter is If null, set to '1.1'.

    $version ? $version : '1.1'
    

    Additional context

    opened by markyou-dev 7
  • StreamWrapper streams are always seekable

    StreamWrapper streams are always seekable

    PHP version: 8.1.11

    Description

    Resources created by StreamWrapper::getResource are always seekable, even if the underlying Stream object, is not.

    How to reproduce

    
    use Psr\Http\Message\StreamInterface;
    use GuzzleHttp\Psr7\StreamWrapper;
    
    class TestStream implements StreamInterface
    {
        public function __toString()
        {
            return $this->getContents();
        }
    
        public function close()
        {
        }
    
        public function detach()
        {
            return null;
        }
    
        public function getSize()
        {
            return 0;
        }
    
        public function tell()
        {
            return 0;
        }
    
        public function eof()
        {
            return true;
        }
    
        public function isSeekable()
        {
            return false;
        }
    
        public function seek($offset, $whence = SEEK_SET)
        {
            return false;
        }
    
        public function rewind()
        {
            return false;
        }
    
        public function isWritable()
        {
            return false;
        }
    
        public function write($string)
        {
        }
    
        public function isReadable()
        {
            return true;
        }
    
        public function read($length)
        {
            return '';
        }
    
        public function getContents()
        {
            return '';
        }
    
        public function getMetadata($key = null)
        {
            return null;
        }
    }
    
    $stream = new TestStream();
    $metadata = stream_get_meta_data(StreamWrapper::getResource($stream));
    
    assert($metadata['seekable'] == $stream->isSeekable(), "Stream is not seekable");
    

    Possible Solution

    Throw an exception in StreamWrapper::getResource if non seekable Stream objects are passed as an argument.

    Additional context

    As far as my research went, custom stream wrappers are currently always treated as seekable (which does not make any sense IMHO). So therefore this can only be implemented in Guzzle as soon as support for none seekable custom stream wrappers is implemented in PHP.

    opened by Deltachaos 0
Releases(2.4.3)
  • 2.4.3(Oct 26, 2022)

  • 2.4.2(Oct 25, 2022)

  • 2.4.1(Aug 28, 2022)

  • 2.4.0(Jun 20, 2022)

  • 1.9.0(Jun 20, 2022)

  • 2.3.0(Jun 9, 2022)

  • 2.2.2(Jun 8, 2022)

  • 2.2.1(Mar 20, 2022)

  • 2.2.0(Mar 20, 2022)

  • 2.1.2(Mar 20, 2022)

  • 2.1.1(Mar 20, 2022)

  • 1.8.5(Mar 20, 2022)

  • 1.8.4(Mar 20, 2022)

  • 2.1.0(Oct 6, 2021)

  • 1.8.3(Oct 5, 2021)

  • 2.0.0(Jun 30, 2021)

  • 2.0.0-rc1(Apr 29, 2021)

  • 1.8.2(Apr 26, 2021)

  • 2.0.0-beta1(Mar 21, 2021)

  • 1.8.1(Mar 21, 2021)

  • 1.8.0(Mar 21, 2021)

  • 1.7.0(Sep 30, 2020)

  • 1.6.1(Jul 1, 2019)

    1.6.0 introduced a few type assertions to enforce types defined by PSR-7. Unfortunately that break the library for users not strictly following the PSR-7 standard. Since the users impacted by this change seems to be rather large, this hotfix reverts that change with the note that we will reapply it in 2.0.0, so fixing this is recommended regardless of which version you use.

    Details are in #282 and #283

    Source code(tar.gz)
    Source code(zip)
  • 1.6.0(Jun 30, 2019)

    Version 1.6.0 is released which will likely be the last minor release in 1.x. We're focussing 2.0 now with support for psr/http-factory, PHP 7.2 requirement and type declarations.

    Added

    • Allowed version ^3.0 of ralouphie/getallheaders dependency (#244)
    • Added MIME type for WEBP image format (#246)
    • Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272)

    Changed

    • Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262)
    • Accept port number 0 to be valid (#270)

    Fixed

    • Fixed subsequent reads from php://input in ServerRequest (#247)
    • Fixed readable/writable detection for certain stream modes (#248)
    • Fixed encoding of special characters in the userInfo component of an URI (#253)
    Source code(tar.gz)
    Source code(zip)
  • 1.5.0(Dec 3, 2018)

    After a really long waiting period, 1.5.0 is finally here with the following changes:

    Added

    • Response first-line to response string exception (fixes #145)
    • A test for #129 behavior
    • get_message_body_summary function in order to get the message summary
    • 3gp and mkv mime types

    Changed

    • Clarify exception message when stream is detached

    Deprecated

    • Deprecated parsing folded header lines as per RFC 7230

    Fixed

    • Fix AppendStream::detach to not close streams
    • InflateStream preserves isSeekable attribute of the underlying stream
    • ServerRequest::getUriFromGlobals to support URLs in query parameters

    Several other fixes and improvements.

    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(Feb 21, 2017)

    • Fix Stream::read when length parameter <= 0.
    • copy_to_stream reads bytes in chunks instead of maxLen into memory.
    • Fix ServerRequest::getUriFromGlobals when Host header contains port.
    • Ensure ServerRequest::getUriFromGlobals returns a URI in absolute form.
    • Allow parse_response to parse a response without delimiting space and reason.
    • Ensure each URI modification results in a valid URI according to PSR-7 discussions. Invalid modifications will throw an exception instead of returning a wrong URI or doing some magic.
      • (new Uri)->withPath('foo')->withHost('example.com') will throw an exception because the path of a URI with an authority must start with a slash "/" or be empty
      • (new Uri())->withScheme('http') will return 'http://localhost'
    • Fix compatibility of URIs with file scheme and empty host.
    • Added common URI utility methods based on RFC 3986 (see documentation in the readme):
      • Uri::isDefaultPort
      • Uri::isAbsolute
      • Uri::isNetworkPathReference
      • Uri::isAbsolutePathReference
      • Uri::isRelativePathReference
      • Uri::isSameDocumentReference
      • Uri::composeComponents
      • UriNormalizer::normalize
      • UriNormalizer::isEquivalent
      • UriResolver::relativize
    • Deprecated Uri::resolve in favor of UriResolver::resolve
    • Deprecated Uri::removeDotSegments in favor of UriResolver::removeDotSegments
    Source code(tar.gz)
    Source code(zip)
  • 1.3.1(Jun 24, 2016)

    • Fix Uri::__toString for network path references, e.g. //example.org.
    • Fix missing lowercase normalization for host.
    • Fix handling of URI components in case they are '0' in a lot of places, e.g. as a user info password.
    • Fix Uri::withAddedHeader to correctly merge headers with different case.
    • Fix trimming of header values in Uri::withAddedHeader. Header values may be surrounded by whitespace which should be ignored according to RFC 7230 Section 3.2.4. This does not apply to header names.
    • Fix Uri::withAddedHeader with an array of header values.
    • Fix Uri::resolve when base path has no slash and handling of fragment.
    • Fix handling of encoding in Uri::with(out)QueryValue so one can pass the key/value both in encoded as well as decoded form to those methods. This is consistent with withPath, withQuery etc.
    • Fix ServerRequest::withoutAttribute when attribute value is null.
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Apr 13, 2016)

    • Added remaining interfaces needed for full PSR7 compatibility (ServerRequestInterface, UploadedFileInterface, etc.).
    • Added support for stream_for from scalars.
    • Can now extend Uri.
    • Fixed a bug in validating request methods by making it more permissive.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.3(Feb 18, 2016)

    • Fixed support in GuzzleHttp\Psr7\CachingStream for seeking forward on remote streams, which can sometimes return fewer bytes than requested with fread.
    • Fixed handling of gzipped responses with FNAME headers.
    Source code(tar.gz)
    Source code(zip)
  • 1.2.2(Jan 23, 2016)

    • Added support for URIs without any authority.
    • Added support for HTTP 451 'Unavailable For Legal Reasons.'
    • Added support for using '0' as a filename.
    • Added support for including non-standard ports in Host headers.
    Source code(tar.gz)
    Source code(zip)
Owner
Guzzle
An extensible PHP HTTP client
Guzzle
It validates PSR-7 messages (HTTP request/response) against OpenAPI specifications

NOTICE - THE PACKAGE HAS BEEN CONTRIBUTED TO THE PHP LEAGUE Go to https://github.com/thephpleague/openapi-psr7-validator This package is here for exis

Dmitry Lezhnev 167 Sep 29, 2022
💫 Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan / Vega 是一个用 PHP 编写的 CLI 模式 HTTP 网络框架,支持 Swoole、WorkerMan

Mix Vega 中文 | English Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan Vega 是一个用 PHP 编写的 CLI 模式 HTTP 网络框架,支持 Swoole、Work

Mix PHP 46 Apr 28, 2022
Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

clue/reactphp-http-proxy Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

Christian Lück 43 Dec 25, 2022
PHP Kafka client is used in PHP-FPM and Swoole. PHP Kafka client supports 50 APIs, which might be one that supports the most message types ever.

longlang/phpkafka Introduction English | 简体中文 PHP Kafka client is used in PHP-FPM and Swoole. The communication protocol is based on the JSON file in

Swoole Project 235 Dec 31, 2022
PHP Coroutine HTTP client - Swoole Humanization Library

PHP Coroutine HTTP client - Swoole Humanization Library

swlib 973 Dec 17, 2022
PSR-15 Adapter for InertiaJS

inertia-psr15 Before using this library, is important to know what is Inertia.js, what is it for and how it works, in the official Inertia.js website

Mohamed Cherif Bouchelaghem 28 Oct 26, 2022
Strict PSR-7 implementation used by the Slim Framework

Strict PSR-7 implementation used by the Slim Framework, but you may use it separately with any framework compatible with the PSR-7 standard.

Slim Framework 96 Nov 14, 2022
Spiral Framework is a High-Performance PHP/Go Full-Stack framework and group of over sixty PSR-compatible components

Spiral HTTP Application Skeleton Spiral Framework is a High-Performance PHP/Go Full-Stack framework and group of over sixty PSR-compatible components.

Spiral Scout 152 Dec 18, 2022
A set of PSR-7 object decorators providing useful convenience methods

Slim-Http Slim PSR-7 Object Decorators Installation It's recommended that you use Composer to install this library. $ composer require slim/http This

Slim Framework 136 Sep 29, 2022
An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols. PHP>=5.3.

Workerman What is it Workerman is an asynchronous event-driven PHP framework with high performance to build fast and scalable network applications. Wo

walkor 10.2k Dec 31, 2022
This package provides some basic methods to implement a self updating functionality for your Laravel application. Already bundled are some methods to provide a self-update mechanism via Github or some private repository via http.

This package provides some basic methods to implement a self updating functionality for your Laravel 5 application. Already bundled are some methods to provide a self-update mechanism via Github.

Holger Lösken 311 Dec 31, 2022
High performance HTTP Service Framework for PHP based on Workerman.

webman High performance HTTP Service Framework for PHP based on Workerman. Manual https://www.workerman.net/doc/webman Benchmarks https://www.techempo

walkor 1.3k Jan 2, 2023
基于 mirai-api-http 的 PHP 机器人框架

miraiez 开始使用 请在 mirai-api-http 的配置文件中启用 http 和 webhook 适配器 并将 webhook 适配器的回调地址设置为 webhook.php 的所在地址 例如 http://localhost/webhook.php 完成上述步骤后,请修改 config

null 20 Jan 9, 2023
jojo, another http server written in PHP 8.0

جوجو | jojo جوجو، وب‌سروری در ابعاد جوجه برای کارهای کوچک داستان نوشتن جوجو وب‌سروری که تنظیمات مودم TP-link TD-8811 توی اتاقم رو serve میکنه اسمش mic

Amirhossein Baghaie 6 Dec 25, 2022
This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

Swoole Taiwan 3.9k Jan 8, 2023
MaxPHP HTTP project skeleton.

轻量 • 简单 • 快速 一款基于swoole的组件化的轻量PHP框架,可以用作API开发,方便快速。 主要特性 组件和框架核心分离 基于 Psr7 的 HTTP-Message 基于 Psr11 的容器 基于 Psr14 的事件 基于 Psr15 的中间件 基于 Psr16 的缓存组件,支持 Fi

chengyao 9 Dec 15, 2022
Slim Framework HTTP cache middleware and service provider

Slim Framework HTTP Cache This repository contains a Slim Framework HTTP cache middleware and service provider. Install Via Composer $ composer requir

Slim Framework 107 Dec 15, 2022
Kit is a lightweight, high-performance and event-driven web services framework that provides core components such as config, container, http, log and route.

Kit What is it Kit is a lightweight, high-performance and event-driven web services framework that provides core components such as config, container,

null 2 Sep 23, 2022
🚀 Coroutine-based concurrency library for PHP

English | 中文 Swoole is an event-driven asynchronous & coroutine-based concurrency networking communication engine with high performance written in C++

Swoole Project 17.7k Jan 8, 2023