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

HTTP query string:

PHP cURL POST array format

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

Chủ Đề