Post request using curl in php
1.Step by step
2.Use as a class
by Vincy. Last modified on June 21st, 2022.
PHP cURL is a library that allows clients to access a remote server via a URL. It sends HTTP requests to the endpoint from a different application or component.
It allows inter-application hits to get a response over the network. This mechanism is useful to work with PHP RESTful services, API interactions, and etc.
There are many use case scenarios where PHP cURL post is exactly suited. For example,
This quick example gives a straightforward code to implement a PHP cURL post.
Apart from this, we will see more use case examples of PHP cURL post requests in the upcoming sections.
Part 1 – Basics of PHP cURL
The following are the steps to perform a basic PHP cURL request-response cycle.
How to configure PHP cURL?
PHP contains libcurl library to let the environment work with cURL. This library will be enabled by default.
If not, do the following steps to enable PHP cURL module in your environment.
Set PHP cURL POST requests – Alternate methods
There are many ways to send PHP cURL post parameters.
HTTP query string:
PHP cURL POST array format
Set cURL header options
To set PHP cURL header, the CURLOPT_HTTPHEADER constant is used. A cURL header can have more information. The following keys are some of the examples to add PHP cURL header options.
This program sets the cURL header options to set the content type. There are options to send custom headers also. It is to send non-standard key-value pairs. Use prefix X- to send non-standard headers. Example,
The CURLOPT_HEADER constant is set with boolean true. It is for allowing the header information attached with the return response.
Part 2 – Example use cases
With some basic knowledge, it will be easy to understand the following examples. It deals with some of the use case scenarios of PHP cURL post or get request methods.
HTTP POST form data
PHP cURL allows posting parameters to the server. It uses any one of the methods we discussed earlier to post parameters via cURL.
The following cURL script shows how to post an array to an endpoint URL. The
PHP cURL POST to upload file
It is also possible to upload files to the server via PHP cURL post. The below code shows how to upload an image file to the server.
It prepares the object with the file data. It uses PHP curl_file_create() function to prepare the file post content.
By sending the ‘fileParam’ bundle in this way, the endpoint code can access it via $_FILES array.
Put the following endpoint code in the server. Then hit the endpoint via the above cURL script. The PHP curl post request sends the file input to this endpoint. This PHP code accesses the uploaded file from the $_FILES array.
HTTP GET request to grab a webpage
In the cURL request, the default method is GET. This program calls the server via cURL with the default GET request method.
Unlike PHP cURL POST, it sends data as the query string. To pass parameters to a GET request, it should be built as part of the URL.
It grabs the HTML of the website specified as the cURL endpoint. It prints the response and renders the target website’s HTML in the browser.
Grab website HTML via cURL and write to a file
Instead of printing the website layout to the browser, it can also be written into a file.
This code creates a filehandle and writes the cURL HTML response into a file. It uses the file handle as the reference.
It will be useful if you want to download and save the website HTML into the server permanently.
The PHP file_get_contents() function is also used to grab the content of the target URL.
But, the server configuration should allow reading the content by using this method.
PHP CURL post and receive JSON data
This example shows how to send a PHP cURL post in JSON format. It also receives the cURL response in the format of JSON.
This code guides creating API services to get requests and send responses in JSON format.
This code prepares the JSON response by setting the content-type using PHP header(). It sets the application/json as the content type.
Handle redirects (HTTP 301,302)
The CURLOPT_FOLLOWLOCATION is set to true to perform the 3XX redirect via PHP cURL.
During the redirect, the cURL will send a GET request on successive redirects. To change this, the CURLOPT_POSTREDIR has to be set.
This program sets CURL_REDIR_POST_ALL to send PHP cURL POST requests on successive attempts.
It limits the number of redirects by using the CURLOPT_MAXREDIRS constant.
This program will return more information as shown below.
Writing cURL error logs into a file
Keeping logs is a best practice for audit purposes. When the site is live, sometimes the logs are very useful for debugging also.
Since it is a remote call, logging cURL errors into a file will help to analyze and fix the issue.
This code guides how to log the error that occurred during the PHP cURL post. It uses PHP curl_error() function to
Write cURL log using CURLOPT_STDERR constant
There is an alternate method to log the PHP cURL error into a file. The CURLOPT_STDERR writes the error message with the reference of the file handle.
This program will return the following output.
Part 3 – Creating PHP cURL script to extract images from a website
In this part of the article, we are going to create a end-to-end cURL component. It will do the following to achieve grabbing images from a webpage.
API service class to initiate cURL and create DOM object
This GrabImageAPI class creates PHP DOMDocument instants to load the site HTML.
The constructor initiates cURL and grabs the complete HTML response of the URL. Then, it loads this response into the DOM object.
With the reference of the object, the getWebsiteImage() gets the image source URLs.
This function reads all images by using getElementsByTagName(). By iterating the image data array, it prepares the JSON bundle of image URLs.
Create cURL service to perform routine life cycle operations
This class is nothing but for performing basic curl operations we have seen at the beginning.
The GrabImageAPI constructor includes this service and creates the cURL instance.
Trigger API to grab images via PHP cURL post
This code will hit the API to grab images via PHP cURL post. It requires the API class reference on which it creates the dynamic image gallery using cURL.
This code is useful to create a gallery widget for your external shop independently.
Hope this article helps you to know a deep knowledge about PHP cURL post and other request methods.
The short and end-to-end examples might be useful to create a cURL component for your application.
I welcome your comments to continue giving more value-adds to the learners.
↑ Back to Top
How do you send a POST request on cURL?
For sending data with POST and PUT requests, these are common curl options:.
request type. -X POST. -X PUT..
content type header..
-H "Content-Type: application/x-www-form-urlencoded".
-H "Content-Type: application/json".
data. form urlencoded: -d "param1=value1¶m2=value2" or -d @data.txt..
Can I use cURL in PHP?
cURL is a PHP library and command-line tool (similar to wget) that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.
How does PHP handle cURL request?
php. $url = "https://www.javatpoint.com/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);.
<? ... .
// create cURL resource..
$ch = curl_init() ;.
//set cURL options..
//Run cURL (execute http request).
$res = curl_exec($ch) ;.
// close cURL resource..
How pass JSON data in URL using cURL in PHP?
Send JSON data via POST with PHP cURL Initiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.