DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Why and When to Use GraphQL

Trending

  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • Save To Bookmarks/Favorites
  • DZone's Article Types
  • Java Virtual Threads Under Load: Three Production Limits

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Make a POST Request from PHP With Guzzle

Make a POST Request from PHP With Guzzle

If you make server-side requests to external APIs using PHP, then check this out. It isn't a new thing with PHP, and this post targets newer versions of PHP.

By 
Lorna Mitchell
·
Updated Sep. 19, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
74.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

I work extensively with APIs and a variety of serverside scripting languages, and best practice does change over time. Many of the most popular posts on my blog are10 years old because apparently, I was interesting in 2008. Two in particular from around that time relate to making POST requests from PHP, and I'd do it completely differently today. So, in an attempt to overcome some of the past crimes of the Internet in general and PHP in particular: here's how to make a POST request in PHP, today, in a PHP 7+ world (it probably works in PHP 5 too).

Dependencies: GuzzleHTTP

Guzzle is brilliant. If you make web requests with PHP, use Guzzle. Guzzle actually does a bunch of other things too, but today, we're making a POST request.

Install Guzzle like this:

composer require guzzlehttp/guzzle 

If you are not using Composer yet then I strongly recommend you give it a whirl. The project itself has excellent documentation and there are some excellent guides around such as this one from Scotch. Seriously, do it. This post can wait.

Once the package is installed then you will need this at the top of index.php:

require "vendor/autoload.php"; 

Now we can write some code!

Make a POST Request

Using Guzzle, we create a client, then instruct the client to make requests.

For testing, we can send requests to the excellent httpbin.org, this is an endpoint that will return you some JSON telling you what you sent to it. The code needs to:

  • create a client with the URL
  • send a POST request to /post
  • capture the response and output it (it's pretty printed JSON, you could easily json_decode() this if you wanted)
require "vendor/autoload.php";

$client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]);
$response = $client->post("/post");

echo $response->getBody();

There, we did it! I think this is simpler to write than the old-style Curl equivalents and crucially much easier to read than my second favorite approach, which is to use PHP's streams. Note that you can still pass a context option to Guzzle if you need to.

Send Form Data With Your Post Request

It's pretty unlikely that you'd want to send a POST request, so while I've outlined the process, there's some more detail to look at here.

Here's an example with some form fields being sent as data; run this code and you'll see that httpbin returns this in it's "form" element.

require "vendor/autoload.php";

$client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]);
$options = [
    'form_params' => [
        "fruit" => "apple"
       ]
   ]; 
$response = $client->post("/post", $options);

echo $response->getBody();

This is for a simple form; there's also a multipart parameter if you need that.

Send JSON With Your Post Request

An increasingly common use case for sending HTTP requests is to call APIs, and for that, you probably want to pass JSON. Here's an example that does that:

require "vendor/autoload.php";

$client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]);
$options = [
    'json' => [
        "fruit" => "apple"
       ]
   ]; 
$response = $client->post("/post", $options);

echo $response->getBody();

Look very closely! All that changes is form_params becomes json and Guzzle automagically sorts out headers and JSON encoding and everything for us. If you didn't want the magic, then you can set the body and headers to meet the requirements of the application.

HTTP Requests In the Wild

It's good to keep up with the current best practice in the industry, but this is absolutely NOT the only way to do this! Many APIs also provide an SDK, Frameworks have their own HTTP clients, and it's very likely that quite a few of them use Guzzle under the hood anyway. Hopefully, this showed you one option for a clean and modern way to handle HTTP requests from PHP. Now I'm off to update those old posts with a link to this one!

PHP Requests POST (HTTP)

Published at DZone with permission of Lorna Mitchell. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Why and When to Use GraphQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook