Posted inphp / Ajax / JavaScript / jQuery / Laravel / Programming / Technology

Curl GET And POST Method Calls – PHP Example

simply curl post request php, curl is an open source free command line platform as well as good library for some client side to server side transferring data with base URL. curl is a powerful useful system to transfer data to many types of the protocals. this is a good method to send data between your each websites.
cURL is unrestricted therefor it can be create easy step to call HTTP Request ,also create complex types of the FTP data upload with an authentication, also can create HTTPS requests.

Steps to create curl get post calls :

php cURL is free based web software which you can use to create various lots of the requests using different types of the protocols. PHP has the many option to use cURL and in this big post, i will learn to different examples like as a cURL POST header parameters file json request.

PHP Curl POST and GET Methods
PHP Curl POST and GET Methods

PHP cURL Basics

curl_init();      
curl_setopt();    
curl_exec();      
curl_close();

PHP cURL Header

You can also update custom user define headers in your cURL http requests. For this, i will use the curl_setopt() function.

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Header-Key-first: Header-Value-first',
    'Header-Key-second: Header-Value-second'
));
PHP cURL Multiple Asynchronous Http Requests
PHP cURL Multiple Asynchronous Http Requests

Step1: php curl initialize example

I will basically initialize based on the the php curl by calling curl_init() simple methods. And then this initation i can call curl resources methods.

Step2:

There are lots of the set setting that i can use for different works with curl_setopt() methods.

Example : bool curl_setopt ( $ch_curl , $option , mixed $value );

First argument $ch_curl
A php cURL simple and easy way to handle returned by curl_init().

Second argument is setting $option
The CURLOPT_XXX option to change or update.

Third And Last argument is $value
The data value to be update on option. for example. array or any value

following are the some main PHP CURL Request settings i can use inside curl_setopt() methods

1. CURLOPT_RETURNTRANSFER – update it TRUE to return the results as a data string, if not update this parameter then results will resultings on page then i can use file_get_contents(‘url’) to get results.
Example : curl_setopt($ch_curl, CURLOPT_RETURNTRANSFER, true);

2. CURLOPT_CONNECTTIMEOUT – total Number of seconds to try to connect
Example : curl_setopt($ch_curl, CURLOPT_CONNECTTIMEOUT, 60);

3. CURLOPT_URL – URL to sent curl request.
Example : curl_setopt($ch_curl, CURLOPT_URL, “http://www.pakainfo.com”);

4. CURLOPT_POST – update when sending curl post request.
Example : curl_setopt($ch_curl, CURLOPT_POST, true);

5. CURLOPT_POSTFIELDS – Array of data sent in post.
Example : curl_setopt($ch_curl, CURLOPT_POST, array(“mobile_code” => “M150”, “mobile_price” => “158747”));

6. CURLOPT_TIMEOUT – Number of seconds cURL will take to execute.
Example : curl_setopt($ch_curl, CURLOPT_TIMEOUT, 60);

7. CURLOPT_FRESH_CONNECT – Each curl call be refresh.
Example : curl_setopt($ch_curl, CURLOPT_TIMEOUT, true);

8. CURLOPT_USERPWD – Some rest pages/api required secure more types of the authentication to access, for these cases i will use this setting.
Example : curl_setopt($ch_curl, CURLOPT_USERPWD, “YOURUSERNAME:YOURPASSWORD”);

Step3:

curl_exec() call will execute for curl settings as well as return results.

Step4:

curl_close() will call to free all curl resources.

create GET METHOD REQUEST

Making a GET method call by curl.


create POST METHOD REQUEST

Making a POST method call by curl.

 '9000787 ',
		  'text' => 'dear, welcome to pakainfo.com, 4cgandhi.com and infinityknow.com'
		);
        $api_request_url = "https://www.pakainfo.com";
       
       $ch_curl = curl_init ($api_request_url);
       curl_setopt ($ch_curl, CURLOPT_POST, true);
       curl_setopt ($ch_curl, CURLOPT_POSTFIELDS, $data);
       curl_setopt ($ch_curl, CURLOPT_RETURNTRANSFER, true);
       $results = curl_exec ($ch_curl); 
       
       if(!results){
               die('Error: "' . curl_error($ch_curl) . '" - Code: ' . curl_errno($ch_curl));
           }
       curl_close($crl);
               
  ?>      

create POST METHOD REQUEST WHERE AUTHENTICATION REQUIRED

Making a POST method call by curl.

 "564DSFds$#d4fdfd54f4d54f5df5df",  "text" => "Welcome to our website you have a 1584 points in your walltes, Good Luck");
           
           $ch_curl=curl_init($api_request_url);
           curl_setopt($ch_curl, CURLOPT_POST, true);
           curl_setopt($ch_curl, CURLOPT_POSTFIELDS, $data);
           curl_setopt($ch_curl, CURLOPT_FRESH_CONNECT, true);
           
           curl_setopt($ch_curl, CURLOPT_USERPWD, $AUTH_USERNAME . ":" . $AUTH_PASSWORD);
           
           $results = curl_exec( $ch_curl );
           if(!results){
               die('Error: "' . curl_error($ch_curl) . '" - Code: ' . curl_errno($ch_curl));
           }
           curl_close($ch_curl);
               
  ?>   
       

create POST METHOD REQUEST WHERE AUTHENTICATION REQUIRED POST REQUEST AS JSON

Making a POST method json call by curl.
A POST request is usually made to send user collected data to a server.

  "JTG058",  "text" => "Now you have a login successfully using api.");
            
            $data_string = json_encode($data);
            print_r($data_string);
            
            $ch_curl=curl_init($api_request_url);
            curl_setopt($ch_curl, CURLOPT_POST, true);
            curl_setopt($ch_curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch_curl, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch_curl, CURLOPT_USERPWD, $AUTH_USERNAME . ":" . $AUTH_PASSWORD);
            
            curl_setopt($ch_curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                        
            $results = curl_exec( $ch_curl );
            if(!results){
                die('Error: "' . curl_error($ch_curl) . '" - Code: ' . curl_errno($ch_curl));
            }
            
            curl_close($ch_curl);
                
   ?>             

php send post request curl

$results = httpPost("http://www.pakainfo.com/change.php",
	array("pcode"=>"s4f54df78","pdesc"=>"Great Mobile version8.5")
);

//using php curl (sudo apt-get install php-curl) 
function httpPost($api_request_url, $data){
    $ch_curl = curl_init($api_request_url);
    curl_setopt($ch_curl, CURLOPT_POST, true);
    curl_setopt($ch_curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch_curl, CURLOPT_RETURNTRANSFER, true);
    $results = curl_exec($ch_curl);
    curl_close($ch_curl);
    return $results;
}

//Non ch_curl Method
function httpPost($api_request_url, $data){
	$options = array(
		'http' => array(
     		'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        	'method'  => 'POST',
        	'content' => http_build_query($data)
    	)
    );
	$context  = stream_context_create($options);
	return file_get_contents($url, false, $context);
}

PHP GET/POST request

here simple PHP code to PHP GET/POST request articles learn how to generate as well as setp by step process GET and POST http requests in PHP. I use plain simple core PHP and Laravel and Symfony, Slim or any other frameworks.

HTTP request

The Hypertext Transfer Protocol (HTTP) is an application protocol for collaborative, distributed, hypermedia information systems. HTTP protocol is the foundation of data communication for the World Wide Web.

HTTP GET request

The HTTP GET request method http requests a step by step calling of the particluers resource.

GET requests:

  • have to only be used to http request a resource
  • arguments are displayed in the URL
  • can be cached
  • remain in the browser history
  • can be any types of the custom bookmarked
  • should never be used when dealing with any types of the sensitive data
  • have length limits

HTTP POST request

The HTTP POST http request method sends data to the server side. this is many times used when data uploading a file or when any types of the submitting a fully web form serverside.
POST requests:

  • have to be used to make a resource
  • arguments are not displayed in the URL
  • are never any types of the cached
  • don’t remain in the browser history
  • cannot be any type of the bookmarked
  • can be used when dealing with any types of the sensitive data
  • have no any security length limits

PHP CURL Post and Get request with example

here’s an example of making a POST request using PHP’s cURL library:

$url = 'http://example.com/api'; // The API endpoint URL
$data = array('name' => 'John Doe', 'email' => '[email protected]'); // The data to send as POST request

$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL, $url); // Set the API endpoint URL
curl_setopt($ch, CURLOPT_POST, 1); // Set the request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // Set the POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string
$response = curl_exec($ch); // Execute the request
curl_close($ch); // Close cURL session

echo $response; // Output the response

And here’s an example of making a GET request:

$url = 'http://example.com/api'; // The API endpoint URL

$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL, $url); // Set the API endpoint URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as a string
$response = curl_exec($ch); // Execute the request
curl_close($ch); // Close cURL session

echo $response; // Output the response

Note: In both examples, we use curl_setopt() to set the cURL options. You can set other options as well, such as headers, authentication, SSL, etc.

I hope you get an idea about curl post request php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype