Giter Site home page Giter Site logo

guzzle / guzzle Goto Github PK

View Code? Open in Web Editor NEW
23.0K 452.0 2.4K 9.87 MB

Guzzle, an extensible PHP HTTP client

Home Page: https://docs.guzzlephp.org/

License: MIT License

Makefile 0.58% PHP 97.62% JavaScript 1.72% Dockerfile 0.07%
guzzle psr-7 httpclient curl webservices php http-client requests

guzzle's Introduction

Guzzle

Guzzle, PHP HTTP client

Latest Version Build Status Total Downloads

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

  • Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc...
  • Can send both synchronous and asynchronous requests using the same interface.
  • Uses PSR-7 interfaces for requests, responses, and streams. This allows you to utilize other PSR-7 compatible libraries with Guzzle.
  • Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients.
  • Abstracts away the underlying HTTP transport, allowing you to write environment and transport agnostic code; i.e., no hard dependency on cURL, PHP streams, sockets, or non-blocking event loops.
  • Middleware system allows you to augment and compose client behavior.
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

Help and docs

We use GitHub issues only to discuss bugs and new features. For support please refer to:

Installing Guzzle

The recommended way to install Guzzle is through Composer.

composer require guzzlehttp/guzzle

Version Guidance

Version Status Packagist Namespace Repo Docs PSR-7 PHP Version
3.x EOL (2016-10-31) guzzle/guzzle Guzzle v3 v3 No >=5.3.3,<7.0
4.x EOL (2016-10-31) guzzlehttp/guzzle GuzzleHttp v4 N/A No >=5.4,<7.0
5.x EOL (2019-10-31) guzzlehttp/guzzle GuzzleHttp v5 v5 No >=5.4,<7.4
6.x EOL (2023-10-31) guzzlehttp/guzzle GuzzleHttp v6 v6 Yes >=5.5,<8.0
7.x Latest guzzlehttp/guzzle GuzzleHttp v7 v7 Yes >=7.2.5,<8.4

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.

guzzle's People

Contributors

adrienbrault avatar alexeyshockov avatar carusogabriel avatar cordoval avatar danack avatar dawehner avatar dzcpy avatar fubhy avatar gimler avatar gmponos avatar grahamcampbell avatar guilliamxavier avatar hakre avatar hobodave avatar hussainweb avatar ivank avatar jamiehannaford avatar jeremeamia avatar jeskew avatar kkopachev avatar kosmik-koi avatar mtdowling avatar nyholm avatar pborreli avatar pelepelin avatar sagikazarmark avatar thewilkybarkid avatar thinkscape avatar timwolla avatar tobion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

guzzle's Issues

Add support for status code 422

We're using an API that provides 422 responses for well-formed and understood requests that cannot be completed due to other errors (e.g. duplicate entry). Is it possible to add this to the $statusTexts array.

i've added it locally as 422 => 'Unprocessable Entity',

Add fix for multiple cache control headers

As pointed out by ddeboer, A notice is thrown in Guzzle\Http\Message\AbstractMessage when multiple cache control headers are present in a response. This method must check if there are multiple cache control headers (Guzzle stores the header value as an array when duplicate headers are encountered in a response).

Shortcut for getting and executing a command

You should add something to Guzzle in Guzzle\Service\Client like this...

class Client // extends ...
{
    // ...

    public function __call($method, $args)
    {
        $command = $this->getCommand($method, $args);

        return $this->execute($command);
    }

    // ...
}

That way, in addition to calling commands like...

$command = $s3->getCommand('get_object');
$command->setBucket('test');
$command->setObject('foo');
$result = $s3->execute($command);

...you could also do this...

$result = $s3->getObject(array(
    'bucket' => 'test',
    'object' => 'foo',
));

...which I think a lot of people would like.

(Sorry if I have some of the syntax wrong.)

Correct documentation about filter

The documentation talks about filter attribute instead of filters in the PHP code.

Exemple in guzzlephp.org/guide/service/creating_dynamic_commands.html

filter  CSV list of functions or static functions that modifies a string    @guzzle key filter="strtoupper,strrev"

CurlConstants class file missing?

...doesn't appear to be in the distributed src. It's referenced in:

// src/Guzzle/Service/Client.php
17 use Guzzle\Http\Curl\CurlConstants;

Not sure if this is really a problem or not, but thought I'd point it out.

Notice - Uninitialized string offset: 0

I've got the notice below, after upgrading Goutte.

Notice - Uninitialized string offset: 0 in phar://APPPATH/vendor/Goutte/goutte.phar/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php on line 132

Is this a bug or I do somthing wrong?

Thanks.

See: FriendsOfPHP/Goutte#48

Add Plugin to all Clients from Service Builder

Is there a way to add a Plugin to all clients getting from service builder.

My use case i build a data collector for GuzzlebBundle (Symfony2) the problem is that i must now add my plugin to all clients. So the user use the $this->get('guzzle.service_builder')->get('myClient') to get the client. Is there a simple way or should i must extends the service builder class with my own and extends the get method

Possibility of disabling Expect:100-Continue HTTP header in POST requests.

Check out discussions below:
http://stackoverflow.com/questions/6244578/curl-post-file-behind-a-proxy-returns-error
http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/
http://matthom.com/archive/2008/12/29/php-curl-disable-100-continue-expectation

The problem is in Guzzle\Http\Message\EntityEnclosingRequest line 32
$this->setHeader('Expect', '100-Continue');

There should be possibility disabling it as it causes a lot of problems.
To debug, check curl verbose log - it shouldn't send Expect:100-Continue when request is POST.

Add a history plugin

Add a history HTTP plugin that can be used to track all requests issued through the plugin.

Filters triggered before type validation

On http://guzzlephp.org/guide/service/service_descriptions.html it states a parameter can be configured as follows:

<param name="data" type="type:array" filters="json_encode" location="body" />

However, this throws a Guzzle\Service\Exception\ValidationException with the message "Validation errors: data: Value must be of type array". Digging into Guzzle\Service\Inspector::validateConstraint() it looks $value has already been converted to JSON at this point.

This happens for me on the v2.6.2 tag and on the master branch.

Code generation based on service descriptions

Investigate the possibility of a command line tool that would read service descriptions and generate snippets of code that could be added to a client. For example:

<command name="get_comment" method="GET" path="/comments/{{id}}">
   <doc>Get a comment by ID</doc>
   <param name="id" type="string" required="true" location="path" doc="Comment ID" />
</command>

Would be translated to:

<?php

/**
 * Get a comment by ID 
 *
 * @param string $id Comment ID
 *
 * @return Response|DynamicCommand
 */
public function getComment($id)
{
   $command = $this->getCommand('get_comment', array(
        'id' => $id
    ));

    return $this->getConfig('client.sync') ? $this->execute($command) : $command;
}

The above code could then be added to a client class to make it easier to use the web service. Would be nice to be able to specify whether command parameters are expanded into separate arguments or if an array should be used as an argument for commands with many parameters.

Inconsistent definition of ClientInterface->get()

From abstract ClientInterface.php:

    /**
     * Create a GET request for the client
     *
     * @param string $path (optional) Resource URI of the request.  Use an
     *      absolute path to override the base path, or a relative path to append
     * @param array|Collection $headers (optional) HTTP headers
     * @param string|resource|array|EntityBody $body (optional) Where to store
     *      the response entity body
     *
     * @return RequestInterface
     */
    function get($uri = null, $inject = null);

Note that $body is documented, but missing from method

but it's used in the implementation in Client.php

    public final function get($path = null, $headers = null, $body = null)
    {
        return $this->createRequest('GET', $path, $headers, $body);
    }

Problem with autloading using PHAR on Windows

I have downloaded guzzle.phar from official website and created simple script:

require 'guzzle.phar';```
I get:

Warning: require_once(phar://D:\htdocs\guzzle.phar\vendor\symfony\class-loader\Symfony\Component\ClassLoader\UniversalClassLoader.php) [<a href='function.require-once'>function.require-once</a>]: failed to open stream: phar error: &quot;vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php&quot; is not a file in phar &quot;D:/htdocs/guzzle.phar&quot; in D:\htdocs\guzzle.phar on line 14

I have PHP 5.3.9 with enabled PHAR extension (Windows x64).

change baseinstall dir in PEAR

I suggest to change the base install dir IN PEAR package.xml, so the command pear install guzzle/guzzle install in PEAR_PATH/Guzzle and not in PEAR_PATH/guzzle/Guzzle because sf2 UniversalClassAutoloader (2.0.10) can't find the Guzzle Namespaces when you set
$loader->registerNamespaceFallbacks(explode(':'), get_include_path());

Service definitions cache

Are the service definitions being cached when executing dynamic commands based on a XML definition file (for example)?

Regards,
Christian.

Ship with dependencies

Guzzle does not ship with it's dependencies.

PHP Fatal error: Class 'Symfony\Component\EventDispatcher\EventDispatcher' not found in /var/www/Public/library/Vendors/Guzzle/src/Guzzle/Common/AbstractHasDispatcher.php on line 42

Is it possible for you to git submodule the dependencies for those who don't want to use Phar?

Mixed serialization strategies

The ServiceBuilder uses the magic __sleep() method for serializing, but the ArrayCookieJar uses the Serializable interface. You should probably switch the ServiceBuilder to using the Serializable as well.

Support Retry-After in ExponentialBackoffPlugin

I am trying to add support for HTTP 429 responses to a web service client I am developing. Specifically, I was attempting to specify my own callable $failureCodes function and checking for the header presence in the response.

However, the problem I ran into is that I have no way to handle this with the current implementation of the ExponentialBackoffPlugin. With the current design there is no way for the "should we retry" callback to "tell" the "calculateWait" callback how long to delay. The calculateWait callback can't determine that for itself either since it doesn't have access to the Response object.

The two options I see:

  • The ExponentialBackoffPlugin could natively support 429 and handle Retry-After headers (note: Retry-After is not exclusive to 429 responses)
  • Pass the Response object (if any) to the calculate wait method so that I could check the Retry-After header in my client code

I don't have a problem implementing either: the latter is much simpler, but the former seems like it may be a more robust approach (less client code, and potentially useful to many) albeit greater in scope. Please let me know your thoughts.

Missing var_export in log message

i get this message the headers and the body is Array so here is a var_export missing

guzzle v2.5.0

{{{
[response] HTTP/1.1 400 Bad Request
Date: Thu, 31 May 2012 20:12:52 GMT
Server: Apache
Cache-Control: public, max-age=600
Expires: Thu, 31 May 2012 20:22:52 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,PUT,DELETE,HEAD
Access-Control-Max-Age: 604800
Content-Length: 171
Connection: close
Content-Type: application/json; charset=utf-8

{"errors":[{"message":"Unable to retrieve server info [500]:\nHeaders: Array\n(\n)\nBody: Array\n(\n [error] => couldn't connect to host [7]\n)\n","name":500,"at":""}]} [] []
}}}

Symfony classloader not found in PHAR

Loading the phar with "require_once 'guzzle.phar'" fails:

[Tue Feb 28 08:57:33 2012] [error] [client 127.0.0.1] PHP Warning: require_once(phar://Guzzle/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php): failed to open stream: phar error: "vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php" is not a file in phar "Guzzle" in /home/jzh/git/kasabi-api/lib/guzzle/guzzle.phar on line 3

I think this may be the same as issue #19, but I've got the latest phar (as at 09:00 on 28th Feb 2012 UTC), and I see the same problem..

I'm on Ubuntu 11.10, with PHP 5.3.6 with phar enabled.

The top of the phar contains this (which looks like the updated version from issue #19):

require_once 'phar://Guzzle/vendor/symfony/class-loader/Symfony/Component/ClassLoader/UniversalClassLoader.php';

$classLoader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$classLoader->registerNamespaces(array(
'Guzzle' => 'phar://Guzzle/src',
'Symfony\Component\Validator' => 'phar://Guzzle/vendor/symfony/validator',
'Symfony\Component\EventDispatcher' => 'phar://Guzzle/vendor/symfony/event-dispatcher',
'Doctrine' => 'phar://Guzzle/vendor/doctrine/common/lib',
'Monolog' => 'phar://Guzzle/vendor/monolog/monolog/src'
));
$classLoader->register();

Is there something else that I'm missing?

Cheers, Julian.

Raw Data

Feature request: When making a request with the Guzzle\Http\Request object I need the ability to set/get a raw body/query (as a string). Currently (if I understand correctly) it must be a Guzzle\Common\Collection object with key/val pairing.

This is needed (for example) when making a request to many Google APIs. Currently I'm (without Guzzle, want to switch) doing a cURL request setting CURLOPT_POSTFIELDS to a raw json string.

Late static binding in factory classes please

Guzzle makes use of many factory classes and methods, which I like. The only problem I have is that they do not support late static binding. For example, if I extend the ServiceBuilder class like so

<?php

namespace Foo;
use Guzzle\Service\ServiceBuilder;
class FooBuilder extends ServiceBuilder { /* ... */ }

When I do FooBuilder::factory( /* ... */ ), I do not get an instance of Foo\FooBuilder, I get an instance of Guzzle\Service\ServiceBuilder. The only way to change that is to overwrite the factory method, which is not a great I idea since it contains a great deal of logic.

So, in your factory methods and classes, if you change your return new self( /* ... */ ) statements into new return new static( /* ... */ ), that would make me ecstatic!

Nested POST arrays still doesn't work.

$request->addPostFields(array(
    'foo'=>'bar',
    'nested'=>array(
        'bla'=>0,
        'oh'=>1
    )
));

Excepted query: foo=bar&nested[bla]=0&nested[oh]=1
Result: foo=bar&nested[0]=1

Invalid validation of Response codes

When response object is created constructor validates response code against hardcoded list:

Guzzle\Http\Message\Response

public function __construct($statusCode, $headers = null, $body = null)
    {
        if (!array_key_exists($statusCode, self::$statusTexts)) {
            throw new BadResponseException(
                'Invalid response code: ' . $statusCode
            );
        }
   ...

and if the code is not in the list a BadResponseException is thrown.

This means that there is no way to use custom codes (like in our case), not even to mention that the list is far from the full list of available standard codes.

I see the intention of this list: to provide proper translation mechanism for the codes, however it should not be used for validation, especially when these is no easy way around it.

Create a pluggable test web server interface

The test webserver is currently only implemented in node.js. Create a PHP implementation with instructions that can be run using a different web server (apache, nginx, php-cli, etc). Create an interface and PHPUnit configs for instantiating different test webservers.

Problem with nested array as POST fields.

Consider example:

$request=$this->post('http://example.com');
$request->addPostFields(array(
'a'=>array('b'=>'c')
));```
Result:
Notice: Undefined offset: 0 in D:\library\Guzzle\Http\Message\EntityEnclosingRequest.php on line 130

You need to use "hack":
```<?php
$request=$this->post('http://example.com');
$request->setBody(http_build_query(array(
'a'=>array('b'=>'c')
)));```

Why you didn't use [http_build_query](http://php.net/manual/en/function.http-build-query.php) in Guzzle\Http\QueryString to generate query?

adding a changelog

You should probably add a changelog listing the BC breaks. Or does it already exist somewhere?

composer.json has missing dependencies

I installed guzzle from packagist.org by simply creating a dependency in my project's composer.json (the main reason you're not seeing pull requests from me -- so far). Since the vendor/Doctrine, vendor/Monolog, and vendor/Symfony/Component/ClassLoader folders were empty, It looks like there are some missing dependencies:

"require": {
    "php"                 : ">=5.3.2",
    "doctrine/common"     : "2.1.*",
    "monolog/monolog"     : "1.0.*",
    "symfony/class-loader": "2.0.*"
},

symfony/class-loader may not be configured correctly (not sure by whom) since it loads in

`````` vendor/guzzle/guzzle/vendor/Symfony/class-loader/Symfony/Component/ClassLoaderrather thanvendor/guzzle/guzzle/vendor/Symfony/Component/ClassLoader```
but things seem to be working ok.

Headers sending a picture in a form

I'm submitting a form with a picture. Using a browser I get this:

Content-Disposition: form-data; name="picture"; filename="thepicture.jpg"
Content-Type: image/jpeg

But using guzzle I get this:

Content-Disposition: form-data; name="picture"; filename="C:\Windows\Temp\uplC14D.tmp"
Content-Type: application/octet-stream

Any bug here?

Cookie header key case

So in the refactoring of cookies (2.6.4 -> 2.6.5). The key for the cookie header changed from "Cookie" to "cookie". I know headers should technically be case insensitive. But for one of my scripts running guzzle broke cause they seem to care about the case of the header key.

The rest of the headers sent by guzzle seem to be Cap-Words.

Think changing the header key back from "cookie" to "Cookie" makes sense?

Do you guys consider this a bug or should I find a workaround?

Receiving 411 error when attempting to post empty request

It seems that if I try to post a request without any body, I am getting a 411 error of length required. If it cannot determine the length of the request body, it should set the content length to 0. When I manually set that header, it resolved my issue.

The '@filename' syntax for uploads has serious security implications

In the case where a user supplied URL (or pastebin/etc) is posted to, with user supplied contents you could land up sending private files.

$_POST = array('firstname' => '@/etc/passwd');
$request = $client->post('http://www.abcd.net/callback', null, array (
  'firstname' => $_POST['firstname']
));

Request parameters names containing dots get converted to underscores

Request parameter names can legally contain dots - but they get converted to underscores by the query string processing.

Example:

    $client = new \Guzzle\Http\Client();
    $request = $client->get("http://example.com/search?q=blah&facet.field=class");

will actually send a request like this:

            GET http://example.com/search?q=blah&facet_field=class

where "facet_field" should be "facet.field".

The problem may be caused by the use of the "parse_str" function in Url.php, which will convert spaces and dots into underscores.

Support POST->GET instead of POST->POST following redirects for compatibility.

Consider example:

  • set CURLOPT_FOLLOWLOCATION = true
  • send POST request to page which will redirect you to another page
    Result:
    cURL will redirect to another page using POST method. It's correct way.
    But - usually web browsers change method to GET. It can cause problems with compatibility so it will be good to have possibility changing the way of following redirects.

useful discussion: https://bugs.php.net/bug.php?id=49571

Request parameters with same names get overwritten

The same request parameter name can appear more than once in an http query string - but the processing of the request string means that all but the last occurrence are lost.

Example:

    $client = new \Guzzle\Http\Client();
    $request = $client->get("http://example.com/search?q=blah&facet=class&facet=property");

will result in a request like this being sent:

           http://example.com/search?q=blah&facet=property

but should be:

           http://example.com/search?q=blah&facet=class&facet=property

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.