Post request using curl in php

1.Step by step

  • Initialize the cURL session:
$url = "www.domain.com";
$ch = curl_init($url);
  • If your request has headers like bearer token or defining JSON contents you have to set HTTPHEADER options to cURL:
$token = "generated token code";
curl_setopt(
    $ch, 
    CURLOPT_HTTPHEADER, 
    array(
        'Content-Type: application/json', // for define content type that is json
        'bearer: '.$token, // send token in header request
        'Content-length: 100' // content length for example 100 characters (can add by strlen($fields))
    )
);
  • If you want to include the header in the output set CURLOPT_HEADER to true:
curl_setopt($ch, CURLOPT_HEADER, false);
  • Set RETURNTRANSFER option to true to return the transfer as a string instead of outputting it directly:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  • To check the existence of a common name in the SSL peer certificate can be set to 0(to not check the names), 1(not supported in cURL 7.28.1), 2(default value and for production mode):
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  • For posting fields as an array by cURL:
$fields = array(
    "username" => "user1",
    "password" => "passuser1",
    "gender" => 1
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  • Execute cURL and return the string. depending on your resource this returns output like result=OK:
$result = curl_exec($ch);
  • Close cURL resource, and free up system resources:
curl_close($ch);

2.Use as a class

  • The whole call_cURL class that can be extended:
class class_name_for_call_cURL {
    protected function getUrl() {
        return "www.domain.com";
    }

    public function call_cURL() {
        $token = "generated token code";

        $fields = array(
            "username" => "user1",
            "password" => "passuser1",
            "gender" => 1
        );

        $url = $this->getUrl();
        $output = $this->_execute($fields, $url, $token);
        
        // if you want to get json data
        // $output = json_decode($output);
            
        if ($output == "OK") {
            return true;
        } else {
             return false;
        }
    }

    private function _execute($postData, $url, $token) {
        // for sending data as json type
        $fields = json_encode($postData);

        $ch = curl_init($url);
        curl_setopt(
            $ch, 
            CURLOPT_HTTPHEADER, 
            array(
                'Content-Type: application/json', // if the content type is json
                'bearer: '.$token // if you need token in header
            )
        );
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}
  • Using the class and call cURL:
$class = new class_name_for_call_cURL();
var_dump($class->call_cURL()); // output is true/false

3.One function

  • A function for using anywhere that needed:
function get_cURL() {

        $url = "www.domain.com";
        $token = "generated token code";

        $postData = array(
            "username" => "user1",
            "password" => "passuser1",
            "gender" => 1
        );

        // for sending data as json type
        $fields = json_encode($postData);

        $ch = curl_init($url);
        curl_setopt(
            $ch, 
            CURLOPT_HTTPHEADER, 
            array(
                'Content-Type: application/json', // if the content type is json
                'bearer: '.$token // if you need token in header
            )
        );
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
}
  • This function is usable just by:
var_dump(get_cURL());

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,

  1. Extracting content from a webpage.
  2. Preparing feed from external sources.
  3. SDK-free API’s direct access methods.

This quick example gives a straightforward code to implement a PHP cURL post.

Quick example

 'Jane',
    'dateOfBirth' => '1974-8-17'
);

$curlHandle = curl_init('http://domain-name/endpoint-path');
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postParameter);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);

$curlResponse = curl_exec($curlHandle);
curl_close($curlHandle);

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.

  • Initialize cURL session.
  • Set cURL options.
  • Execute request.
  • Close session.

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.

  1. Open PHP configuration file php.ini
  2. Check for the extension=php_curl.dll initiation.
  3. Remove the semicolon (;) at the beginning of the above line.
  4. Restart the Apache server.

Post request using curl in php

Set PHP cURL POST requests – Alternate methods

There are many ways to send PHP cURL post parameters.

  1. JSON format.
  2. HTTP query string.
  3. POST array format.

JSON format:

HTTP query string:

PHP cURL POST array format

The CURLOPT_POSTFIELDS may have a PHP array to pass the parameters to the endpoint.

"value1", "key2"=>"value2");
 
?>

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.

  • Accept-Encoding
  • Cache-Control
  • Host
  • Content-Type
  • Accept-Language
  • User-Agent

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,

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-key: value'
));

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 CURLOPT_POST and the CURLOPT_POSTFIELDS are to send the values via PHP cURL post.


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.

 $fileContent);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST,true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result=curl_exec ($curl);
curl_close ($curl);

print $result;
?>

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.

php-curl-post-file-endpoint.php


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.

 "Jane",
    "last_name" => "Mclane",
    "email" => "",
    "addresses" => array(
        "address1" => "21/A",
        "city" => "Los Angels",
        "country" => "USA",
        "phone" => "555-1212",
        "pincode" => "82312"
    )
);
$encodedData = json_encode($data);
$curl = curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData);
$result = curl_exec($curl);
curl_close($curl);
print $result;

This code prepares the JSON response by setting the content-type using PHP header(). It sets the application/json as the content type.

php-curl-post-endpoint-json.php

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.

 "Jane",
    "last_name" => "Mclane"
);
$encodedData = json_encode($data);
$curl = curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData);


curl_setopt($curl, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl,CURLOPT_MAXREDIRS, 3);
$result = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
print "
";
print_r($info);
print_r($result);

This program will return more information as shown below.

  • Redirects count.
  • Time to redirect.
  • A header with the 3XX status.

Post request using curl in php

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.

Post request using curl in php

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.

  1. Create API service to instantiate DOM to load response.
  2. Create cURL service to instantiate, configure and execute requests.
  3. Read cURL response and load it into the DOM object.
  4. Get the image source URL by accessing the DOM object.
  5. Create a photo gallery by using the PHP cURL response array.

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.

Service/GrabImageAPI.php

executeCurl();
        $this->dom = new DOMDocument();
        @$this->dom->loadHTML($siteHTML);
    }

    function getWebsiteImage()
    {
        // Parse DOM to get Images
        $images = $this->dom->getElementsByTagName('img');
        
        $imageSourceURL = array();
        for ($i = 0; $i < $images->length; $i ++) {
            $image = $images->item($i);
            $src = $image->getAttribute('src');
            
            if(filter_var($src, FILTER_VALIDATE_URL)) {
                $imageSourceURL[] = $src;
            }
        }
        $imageSourceJSON = json_encode($imageSourceURL);
        
        return $imageSourceJSON;
    }
}

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.

Service/CurlService.php

endpoint = $url;
        $this->curl = curl_init($this->endpoint);
    }
    
    function setCurlOption()
    {
        curl_setopt($this->curl, CURLOPT_HEADER, 0);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, 1);
    }
    
    function executeCurl()
    {
        $this->setCurlOption();
        $this->response = curl_exec($this->curl);
        curl_close($this->curl);
        return $this->response;
    }
}

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.

php-curl-grab-image.php

getWebsiteImage();
    $imageSourceArray = json_decode($imageSource, true);
} catch (Exception $e) {
    // Handle API request failure
    $statusMsg = $e->getMessage();
    print $statusMsg;
    exit;
}

// Iterate response and form image gallery in UI
foreach($imageSourceArray as $imageSource) {
    ?>
    
    

Conclusion

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.
Download

↑ 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.