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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Designing a Java Connector for Software Integrations
  • AI’s Role in Everyday Development
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • How Trustworthy Is Big Data?
  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 user avatar
Lorna Mitchell
·
Updated Sep. 19, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
73.3K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. 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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!