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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • How to Automate Restful APIs Using Jayway Library
  • 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

Trending

  • TypeScript: Useful Features
  • Deploy a Session Recording Solution Using Ansible and Audit Your Bastion Host
  • Database Monitoring: Key Metrics and Considerations
  • How TIBCO Is Evolving Its Platform To Embrace Developers and Simplify Cloud Integration
  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.

Lorna Mitchell user avatar by
Lorna Mitchell
·
Updated Sep. 19, 18 · Tutorial
Like (1)
Save
Tweet
Share
71.47K 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 Automate Restful APIs Using Jayway Library
  • 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

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: