A Chainable, REST Friendly, PHP HTTP Client. A sane alternative to cURL.

Related tags

HTTP httpful
Overview

Httpful

Build Status Total Downloads

Httpful is a simple Http Client library for PHP 7.2+. There is an emphasis of readability, simplicity, and flexibility – basically provide the features and flexibility to get the job done and make those features really easy to use.

Features

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS)
  • Custom Headers
  • Automatic "Smart" Parsing
  • Automatic Payload Serialization
  • Basic Auth
  • Client Side Certificate Auth
  • Request "Templates"

Sneak Peak

Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects.

// Make a request to the GitHub API with a custom
// header of "X-Trvial-Header: Just as a demo".
$url = "https://api.github.com/users/nategood";
$response = \Httpful\Request::get($url)
    ->expectsJson()
    ->withXTrivialHeader('Just as a demo')
    ->send();

echo "{$response->body->name} joined GitHub on " .
                        date('M jS', strtotime($response->body->created_at)) ."\n";

Installation

Composer

Httpful is PSR-0 compliant and can be installed using composer. Simply add nategood/httpful to your composer.json file. Composer is the sane alternative to PEAR. It is excellent for managing dependencies in larger projects.

{
    "require": {
        "nategood/httpful": "*"
    }
}

Install from Source

Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like Symfony's. Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply require("bootstrap.php")).

Build your Phar

If you want the build your own Phar Archive you can use the build script included. Make sure that your php.ini has the Off or 0 value for the phar.readonly setting. Also you need to create an empty downloads directory in the project root.

Contributing

Httpful highly encourages sending in pull requests. When submitting a pull request please:

  • All pull requests should target the dev branch (not master)
  • Make sure your code follows the coding conventions
  • Please use soft tabs (four spaces) instead of hard tabs
  • Make sure you add appropriate test coverage for your changes
  • Run all unit tests in the test directory via phpunit ./tests
  • Include commenting where appropriate and add a descriptive pull request message

Changelog

0.3.2

  • REFACTOR PR #276 Add properly subclassed, more descriptive Exceptions for JSON parse errors

0.3.1

  • FIX PR #286 Fixed header case sensitivity

0.3.0

  • REFACTOR Dropped support for dead versions of PHP. Updated the PHPUnit tests.

0.2.20

  • MINOR Move Response building logic into separate function PR #193

0.2.19

  • FEATURE Before send hook PR #164
  • MINOR More descriptive connection exceptions PR #166

0.2.18

0.2.17

  • FEATURE PR #144 Adds additional parameter to the Response class to specify additional meta data about the request/response (e.g. number of redirect).

0.2.16

  • FEATURE Added support for whenError to define a custom callback to be fired upon error. Useful for logging or overriding the default error_log behavior.

0.2.15

  • FEATURE I #131 Support for SOCKS proxy

0.2.14

  • FEATURE I #138 Added alternative option for XML request construction. In the next major release this will likely supplant the older version.

0.2.13

  • REFACTOR I #121 Throw more descriptive exception on curl errors
  • REFACTOR I #122 Better proxy scrubbing in Request
  • REFACTOR I #119 Better document the mimeType param on Request::body
  • Misc code and test cleanup

0.2.12

  • REFACTOR I #123 Support new curl file upload method
  • FEATURE I #118 5.4 HTTP Test Server
  • FIX I #109 Typo
  • FIX I #103 Handle also CURLOPT_SSL_VERIFYHOST for strictSsl mode

0.2.11

  • FIX I #99 Prevent hanging on HEAD requests

0.2.10

  • FIX I #93 Fixes edge case where content-length would be set incorrectly

0.2.9

  • FEATURE I #89 multipart/form-data support (a.k.a. file uploads)! Thanks @dtelaroli!

0.2.8

  • FIX Notice fix for Pull Request 86

0.2.7

  • FIX I #86 Remove Connection Established header when using a proxy

0.2.6

  • FIX I #85 Empty Content Length issue resolved

0.2.5

  • FEATURE I #80 I #81 Proxy support added with useProxy method.

0.2.4

  • FEATURE I #77 Convenience method for setting a timeout (seconds) $req->timeoutIn(10);
  • FIX I #75 I #78 Bug with checking if digest auth is being used.

0.2.3

  • FIX Overriding default Mime Handlers
  • FIX PR #73 Parsing http status codes

0.2.2

  • FEATURE Add support for parsing JSON responses as associative arrays instead of objects
  • FEATURE Better support for setting constructor arguments on Mime Handlers

0.2.1

  • FEATURE PR #72 Allow support for custom Accept header

0.2.0

  • REFACTOR PR #49 Broke headers out into their own class
  • REFACTOR PR #54 Added more specific Exceptions
  • FIX PR #58 Fixes throwing an error on an empty xml response
  • FEATURE PR #57 Adds support for digest authentication

0.1.6

  • Ability to set the number of max redirects via overloading followRedirects(int max_redirects)
  • Standards Compliant fix to Accepts header
  • Bug fix for bootstrap process when installed via Composer

0.1.5

  • Use DIRECTORY_SEPARATOR constant PR #33
  • PR #35
  • Added the raw_headers property reference to response.
  • Compose request header and added raw_header to Request object.
  • Fixed response has errors and added more comments for clarity.
  • Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616.
  • Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details.
  • Added default User-Agent header
  • User-Agent: Httpful/0.1.5 + curl version + server software + PHP version
  • To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks.
  • Completed test units for additions.
  • Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier.

0.1.4

  • Add support for CSV Handling PR #32

0.1.3

  • Handle empty responses in JsonParser and XmlParser

0.1.2

  • Added support for setting XMLHandler configuration options
  • Added examples for overriding XmlHandler and registering a custom parser
  • Removed the httpful.php download (deprecated in favor of httpful.phar)

0.1.1

  • Bug fix serialization default case and phpunit tests

0.1.0

  • Added Support for Registering Mime Handlers
  • Created AbstractMimeHandler type that all Mime Handlers must extend
  • Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes
  • Added ability to register new mime handlers for mime types
Comments
  • Hard to find improvements

    Hard to find improvements

    Wow you've been busy! =)

    I took this down a few weeks ago but only got around to checking it out now. Read through Response class and saw body, raw_body, headers and alarms went off NOOOO where's raw_header??? ...and then I saw $this->raw_headers were being populated in the constructor and it was only the property reference that was missing.

    I quickly scanned my source and saw ahhh I can help with composer package etc, sure there are things I can do but when I came back to fork I realized that I was going to have to look deeper if I wanted to help. It was not easy but I think I found a few items that will be useful.

    The commit messages will have additional comments but these should be among them.

    • Added the raw_headers property reference to response
    • Compose request header and added raw_header to Request object.
    • Fixed response has errors and added more comments for clarity.
    • Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616.
    • Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details.
    • Added default User-Agent header.
      • User-Agent: HttpFul/1.0 you might want to tweak the name and version number.
      • `(cURL/?.?.? (host) if all else fails but it should be able to find the curl version from uhm curl_version() I guess.
      • Then we get PHP/5.3.8 for example which should get populated from the core provided PHP_VERSION constant.
      • Then we check if we have $_SERVER['SERVER_SOFTWARE'] and remove PHP from there should it exist.
      • If SERVER_SOFTWARE is unavailable we are more than likely using CLI so check for TERM_PROGRAM and TERM_PROGRAM_VERSION from $_SERVER.
      • Finally add the HTTP_USER_AGENT string if it exists and close the support software section with ')' to wrap this up as the perfect User-Agent string to verify any issues we might have.
    • To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks.
    • Completed test units for all the additions and a few extra ones see @a23e8c301dbe501ccb934c0ff7e690a334bd81b4 and @1741fd8427f8015c391023fcca844fa0641cc6b7 for details.
    • Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier.

    I like what you've done to this implementation but maybe a tad too user friendly for my liking, is there such a thing as too user friendly?.. not that this should demotivate you there definitely is a place for this. I might steel a few concepts if you don't mind =)

    The huge focus on the request headers was different and it works quite intuitively but I don't see how this is an improvement on say:

    <?php $request->header['X-My-Awesome-Header'] = 'this works fine';
    

    Maybe this is where my gripe with the user friendliness comes in, I want to know that's my header and I want to set it as I expect it without the camelCasing and "with" parsing and all the other bells getting in the way. Maybe if I sleep over it I will see things differently... we'll see.

    Keep up the good work!

    opened by nickl- 12
  • Upload feature

    Upload feature

    Implemented basic feature to upload files.

    Use:

    \Httpful\Request::post($this->url) ->body(array()) ->attach(array('indexToPost' => '/path/to/file')) ->send()

    The content type should be multipart/form-data Method should be POST Data should be array

    opened by dtelaroli 10
  • Issue with httpful.phar include

    Issue with httpful.phar include

    I am using the latest version(httpful-0.2.0.phar) of HTTPFul phar. On the hosted setup I get following problem: I have included phar as include "./httpful.phar"; .......................... PHP Warning: include(): Failed opening 'phar://httpful.phar/Httpful/Bootstrap.php' for inclusion (include_path='.:') in /var/www/tut/soapsync/httpful.phar on line 4 PHP Fatal error: Class 'Httpful\Bootstrap' not found in /var/www/tut/soapsync/httpful.phar on line 5

    while on my local(dev) setup it works fine.

    opened by rkshakya 10
  • HTTP/1.1 100 continue

    HTTP/1.1 100 continue

    httpful don't seem to handle "100 continue" reply's

    I have added a new header to line 734 in Response.php :

        $headers[] = $accept;
    +  $headers[] = 'Expect:'; 
    

    There's a lot of talk about this issue on the net, see eg.

    http://www.infernodevelopment.com/expect-100-continue-header-twitter-api-error-using-php-curl http://www.iandennismiller.com/blog/2009/09/curl-http1-1-100-continue-and-multipartform-data-post/

    opened by tomhelmer 9
  • Fatal error: Class 'Request' not found

    Fatal error: Class 'Request' not found

    Hello

    Maybe I'm just new at this but I get this error no matter if I use the .phar or install using Composer (successfully). Monolog works so I don't think it's a problem with Composer. I've tried downgrading but to no avail, still the same error:

    Fatal error: Class 'Request' not found in

    I've tried both the Twitter and Google samples but it seems to be some kind of include problem?

    opened by alexlangberg 8
  • Update src/Httpful/Response/Headers.php

    Update src/Httpful/Response/Headers.php

    Update src/Httpful/Response/Headers.php If a header appears more than once, it must also be able to  be represented as a single header with a comma-separated list of values.  We transform accordingly.

    Well, the cookies have commas on them on the date field so i'm using a double pipe for delimiter.

    Set-Cookie: cookie_1=42de533-b4d2-4f28-8982-ccda555061a8; Domain=www.mydomain.com; Expires=Tue, 12-Feb-13 17:10:28 GMT; Path=/; HttpOnly  Set-Cookie: cookie_2=somevalue; Domain=www.mydomain.com; Expires=Tue, 12-Feb-13 15:10:28 GMT; Path=/; HttpOnly

    BUG 
    opened by papi83dm 8
  • Add convenience methods for appending parameters to query string.

    Add convenience methods for appending parameters to query string.

    Instead of specifying all of the query string parameters directly in the URL, you can now do

    Request::get("http://api.flickr.com/services/rest/")
        ->param("api_key", $apiKey)
        ->param("format", "json")
        ->param("nojsoncallback", 1);
        ->param("photo_id", $photoId)
        ->param("method", "flickr.photos.getInfo")
    

    which I would consider more elegant and concise than creating one, very long URL with all of the parameters embedded, and their values interpolated in the string.

    FEATURE-REQUEST 
    opened by pbogdan 8
  • phar file not available in the mentioned location

    phar file not available in the mentioned location

    Hi, The phar file is apparently not located at https://github.com/downloads/nategood/httpful/httpful.phar Could you please provide me the location of the same? Thanks

    opened by rkshakya 8
  • Empty body

    Empty body

    Hi!

    I've noted this bug after commit https://github.com/nategood/httpful/commit/ef6a59c9b4c906687d47ce7dff93587674fcee53

    If you set 'Content-Length' to 0 some webserver/library won't see the body...

    I've reverted to previous commit and everything works fine.

    opened by racingDeveloper 7
  • Add xml support

    Add xml support

    I'm still learning GH's PullRequest feature, and the diff seems longer than I expected, but it should do the trick: XML serializing and parsing in Httpful.

    opened by zackdouglas 7
  • Add logging support and test server(requires PHP 5.4) for tests

    Add logging support and test server(requires PHP 5.4) for tests

    I added logging support(with a user-specifiable logging function) and a test server to the HttpfulTests script.

    Requires PHP 5.4 for the built in server. Might be advisable to do PHP version checking to make sure the tests still work on PHP < 5.4.

    opened by zbuc 6
  • Documentation ?????

    Documentation ?????

    Hello devs!

    I'm having difficulties finding how to achieve what I want using this library. Is there any known documentation for this library. Please help me finding it.

    Thank You.

    opened by rootgithubbeta 1
  • calling expectsJson() before body() of a post request breaks response parsing

    calling expectsJson() before body() of a post request breaks response parsing

    $response = \Httpful\Request::post($url)
    ->expectsJson()
    ->body(['abc'=>123], \Httpful\Mime::FORM)
    ->send();
    

    results in incorrect response body parsing, for example: Array (size=1) '{"exampleResponseFromServer":"data processed successfully"}' => string '' (length=0) (the entire raw response body is put in an array key and the array value is empty string)

    When ->expectsJson() is called after ->body() the response JSON is parsed correctly.

    opened by lukemim 0
  • Trying to get in touch regarding a security issue

    Trying to get in touch regarding a security issue

    Hey there!

    I belong to an open source security research community, and a member (@ay-kay) has found an issue, but doesn’t know the best way to disclose it.

    If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

    Thank you for your consideration, and I look forward to hearing from you!

    (cc @huntr-helper)

    opened by JamieSlome 2
  • Allow curl to decode the response

    Allow curl to decode the response

    This PR is trying to fix the issue with a compressed response, in my case, it was "gzip" compression. For example, if we get "Content-Encoding: gzip" from the server side we will get the exception with the message "Unable to parse the response as JSON: Control character error, possibly incorrectly encoded"

    The point is to allow curl to decode the response automatically if it is compressed and then later every parser can continue to do their jobs without any issue.

    Please let me know what do you think.

    Thanks!

    opened by stfndamjanovic 1
  • Warnings in PHP 8.1

    Warnings in PHP 8.1

    Can you add return types for PHP 8.1 to remove warnings?

    In that line https://github.com/nategood/httpful/blob/master/src/Httpful/Response/Headers.php#L47 return type bool should be added to do that.

    Now it ends up with:

    Method "ArrayAccess::offsetUnset()" might add "void" as a native return type declaration in the future. Do the same in implementation "Httpful\Response\Headers" now to avoid errors or add an explicit @return annotation to suppress this message.

    Return type of Httpful\Response\Headers::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

    Return type of Httpful\Response\Headers::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice

    • Other methods defined in \ArrayAccess and \Countablealso should be fixed.
    opened by qrtyzmng 4
Owner
Nate Good
CTO
Nate Good
Simple HTTP cURL client for PHP 7.1+ based on PSR-18

Simple HTTP cURL client for PHP 7.1+ based on PSR-18 Installation composer require sunrise/http-client-curl QuickStart composer require sunrise/http-f

Sunrise // PHP 15 Sep 5, 2022
PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs

PHP Curl Class: HTTP requests made easy PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs. Installation Requirements Quic

null 3.1k Jan 5, 2023
Online tool to convert `curl` requests to Laravel `Http` requests

curl Converter Another bit of automation from Shift to convert curl requests to Laravel Http requests. This project is a WIP. You may follow along wit

Laravel Shift 66 Dec 17, 2022
PHP Curl ile letgo api kütüphanesi oluşturuldu. php ile letgo giriş yap.

Kendi LETGO API ile işlemler gerçekleştirelim. // email işlemleri $server = 'imap.gmail.com'; $user = '[email protected]'; $pass = 'password'; $port = 9

Görkem Bayraktar 2 Nov 3, 2022
Declarative HTTP Clients using Guzzle HTTP Library and PHP 8 Attributes

Waffler How to install? $ composer require waffler/waffler This package requires PHP 8 or above. How to test? $ composer phpunit Quick start For our e

Waffler 3 Aug 26, 2022
The best php curl library.

中文文档 About Implemented by using php-curl internal io event with high performance,high universality,high extensibility which especially suitable for ma

Ares 431 Dec 12, 2022
Custom PHP curl library for the Laravel 5 framework - developed by Ixudra

ixudra/curl Custom PHP cURL library for the Laravel 4 or 5 framework - developed by Ixudra. The package provides an easy interface for sending cURL re

Jan Oris 556 Jan 6, 2023
PHP cURL for feed Instagram Graph API

php-curl-instagram-graph PHP cURL for feed Instagram Graph API Script made based on the new (2020) Instagram API that requires authorization token gen

null 12 Apr 13, 2022
Simple PHP curl wrapper class

php-curl The smallest possible OOP wrapper for PHP's curl capabilities. Note that this is not meant as a high-level abstraction. You should still know

Andreas Lutro 243 Dec 5, 2022
This library provides an object-oriented wrapper of the PHP cURL extension

PHP Curl Class This library provides an object-oriented wrapper of the PHP cURL extension. If you have questions or problems with installation or usag

PHP MOD 321 Dec 30, 2022
The best php curl library.

中文文档 About Implemented by using php-curl internal io event with high performance,high universality,high extensibility which especially suitable for ma

Ares 431 Dec 12, 2022
Plug & Play [CURL + Composer Optional], Proxy as a Service, Multi-tenant, Multi-Threaded, with Cache & Article Spinner

?? .yxorP The SAAS(y), Multitenancy & Augmenting Web Proxy Guzzler is a 100% SAAS(y) plug-and-play (PHP CURL+Composer are Optional) solution that leverages SAAS architecture to provide multi-tenancy, multiple threads, caching, and an article spinner service.

4D/ҵ.com Dashboards 12 Nov 17, 2022
Retrofit implementation in PHP. A REST client for PHP.

Retrofit PHP Retrofit is a type-safe REST client. It is blatantly stolen from square/retrofit and implemented in PHP. ❗ UPGRADE NOTICE ❗ Version 3 int

null 153 Dec 21, 2022
Guzzle, an extensible PHP HTTP client

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

Guzzle 22.3k Jan 2, 2023
PHP's lightweight HTTP client

Buzz - Scripted HTTP browser Buzz is a lightweight (<1000 lines of code) PHP 7.1 library for issuing HTTP requests. The library includes three clients

Kris Wallsmith 1.9k Jan 4, 2023
HTTPlug, the HTTP client abstraction for PHP

HTTPlug HTTPlug, the HTTP client abstraction for PHP. Intro HTTP client standard built on PSR-7 HTTP messages. The HTTPlug client interface is compati

The PHP HTTP group 2.4k Dec 30, 2022
Unirest in PHP: Simplified, lightweight HTTP client library.

Unirest for PHP Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the

Kong 1.3k Dec 28, 2022
↪️ Bypass for PHP creates a custom HTTP Server to return predefined responses to client requests

Bypass for PHP provides a quick way to create a custom HTTP Server to return predefined responses to client requests.Useful for tests with Pest PHP or PHPUnit.

CiaReis 101 Dec 1, 2022
A PHP proxy to solve client browser HTTP CORS(cross-origin) restrictions.

cors-bypass-proxy A PHP proxy to solve client browser HTTP CORS(cross-origin) restrictions. A simple way to solve CORS issue when you have no access t

Gracious Emmanuel 15 Nov 17, 2022