Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to Use Postman for Sending POST Requests?
Next article icon

How to send a POST Request with PHP ?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In web development, sending POST requests is a common practice for interacting with servers and exchanging data. PHP, a versatile server-side scripting language, provides various approaches to accomplish this task. This article will explore different methods to send POST requests using PHP.

Table of Content

  • Using file_get_contents() and stream_context_create() Functions
  • Leveraging the cURL Library
  • Utilizing the HTTP_Request2 Class

Using file_get_contents() and stream_context_create() Functions

This approach involves creating a stream context to configure the request and then using file_get_contents() function to perform the POST request. It is a basic method suitable for simple scenarios.

Example:

PHP
<?php    // Define the URL and data $url = 'https://example.com/'; $data = ['key' => 'value'];  // Prepare POST data $options = [     'http' => [         'method'  => 'POST',         'header'  => 'Content-type: application/x-www-form-urlencoded',         'content' => http_build_query($data),     ], ];  // Create stream context $context  = stream_context_create($options);  // Perform POST request $response = file_get_contents($url, false, $context);  // Display the response echo $response;  ?> 

Here, define the target URL and the data to be sent. Create a stream context with the appropriate POST headers and data. Use file_get_contents with the created context to perform the POST request. Display the received response.

Output:

wdw

Leveraging the cURL Library

The cURL library is a powerful tool for making HTTP requests. PHP provides a curl_init() function to initialize a cURL session, allowing you to configure and execute POST requests with fine-grained control.

Example:

PHP
<?php  // Specify the URL and data $url = 'https://example.com/'; $data = ['key' => 'value'];  // Initialize cURL session $ch = curl_init();  // Set cURL options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Execute cURL session $response = curl_exec($ch);  // Check for cURL errors if ($response === false) {     die('Error occurred while fetching the data: '          . curl_error($ch)); }  // Close cURL session curl_close($ch);  // Display the response echo $response;  ?> 

Define the target URL and the data to be sent. Initialize a cURL session using curl_init() function. Set cURL options, including the POST method, POST data, and return transfer option. Execute the cURL session using curl_exec() function. Close the cURL session with curl_close() function. Display the received response.

Output:

wdw

Utilizing the HTTP_Request2 Class

For advanced scenarios, the HTTP_Request2 class from the PEAR package offers a convenient object-oriented approach. It provides features like handling redirects, cookies, and custom headers.

Example:

PHP
<?php  // Install PEAR's HTTP_Request2 package // using Composer // composer require pear/http_request2  // Include Composer autoload require_once 'vendor/autoload.php';  // Specify the URL and data $url = 'https://example.com/'; $data = ['key' => 'value'];  // Create HTTP_Request2 object $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $request->addPostParameter($data);  // Send the request and get the response try {     $response = $request->send()->getBody();        // Display the response     echo $response; } catch (HTTP_Request2_Exception $e) {     die('Error occurred while fetching the data: '          . $e->getMessage()); }  ?> 

Install the HTTP_Request2 package using Composer. Include the Composer autoload file. Define the target URL and the data to be sent. Create an HTTP_Request2 object with the POST method and parameters. Send the request using send() and retrieve the response with getBody() Function. Display the received response.

Output:

wdw


Next Article
How to Use Postman for Sending POST Requests?

F

falgunbofs
Improve
Article Tags :
  • Web Technologies
  • PHP
  • Geeks Premier League
  • PHP-Questions
  • Geeks Premier League 2023

Similar Reads

  • How to Send an HTTP POST Request in JS?
    We are going to send an API HTTP POST request in JavaScript using fetch API. The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request. Th
    2 min read
  • How to receive JSON POST with PHP ?
    In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features: php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data
    2 min read
  • How to Send WebSocket Requests with Postman ?
    This article will show how to send WebSocket requests in Postman. Postman is a popular collaborative platform for API development. It offers different tools for designing, debugging, and testing an API, making it more efficient. WebSocket is an advanced technology used for real-time bidirectional co
    3 min read
  • How to Use Postman for Sending POST Requests?
    Understanding how to send a POST request in Postman is a crucial skill for any developer or tester. POST requests are typically used for submitting data to a server, such as creating new resources or uploading files. What is a POST Request?A POST request is an HTTP request method used for sending da
    4 min read
  • How to set header request in Postman?
    Postman is a powerful API development tool that offers a feature known as environment variables. These variables are used for efficient testing and development of APIs by allowing users to manage dynamic values across requests easily. In this article, we will learn How you can set header requests in
    2 min read
  • How to create and send POST requests in Postman?
    Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, and convert save the API to code for various languages(like JavaScript, and Python).
    2 min read
  • How to create and send GET requests in Postman?
    Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, converting the API to code for various languages(like JavaScript, Pyt
    1 min read
  • How to send a PUT/DELETE request in jQuery ?
    To send PUT/DELETE requests in jQuery, use the .ajax() method, specifying the type as PUT or DELETE. This enables updating or deleting server resources via AJAX. Unlike .get() and .post(), jQuery lacks dedicated .put() and .delete() methods. ApproachTo make a PUT or DELETE requests in jQuery we can
    2 min read
  • Send Parameters to POST Request FastAPI
    In the world of web development and API creation, sending parameters via a POST request is a fundamental operation. FastAPI, a modern Python web framework, simplifies this process and allows developers to build efficient and scalable APIs. In this article, we will explore the theory and practical as
    3 min read
  • How to Send FormData Objects with Ajax-requests in jQuery ?
    In this article, we will see how can we send formData objects with Ajax requests by using jQuery. To send formData, we use two methods, namely, the FormData() method and the second method is serialize() method. The implementation of Ajax to send form data enables the submission of data to the server
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences