How To POST JSON Data with PHP cURL

The PHP cURL is a library used for making HTTP requests. In order to use PHP cURL, you must have installed and enabled libcurl module for PHP on your system. In this tutorial, you will learn how to POST JSON data with PHP cURL requests. Basically, there are 4 steps involved to complete a cURL request using PHP.

  • curl_init — The first step is to initializes a new session of cURL and return a cURL handle to other functions.
  • curl_setopt — The second step is to set options for a cURL session handle. All these settings are very well explained at curl_setopt().
  • curl_exec — In third step it perform a cURL session based on above options set.
  • curl_close — The last step is to close a cURL session initialize by curl_init() and free all resources. Also deleted the cURL handle.
    Let’s use the below sample code to create a POST request with PHP cURL.
<?php
// A sample PHP Script to POST data using cURL
// Data in JSON format
 
$data = array(
    'username' => 'tecadmin',
    'password' => '012345678'
);

$payload = json_encode($data);
 
// Prepare new cURL resource
$ch = curl_init('https://api.example.com/api/1.0/user/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
// Submit the POST request
$result = curl_exec($ch);
 
// Close cURL session handle
curl_close($ch);
?>

The main thing is that the request must be a POST request with properly json-encoded data in the body. The headers must properly describe the post body.

参考:https://tecadmin.net/post-json-data-php-curl/


» 本文链接:https://blog.daoshengtech.cn/archives/2068.html
» 转载请注明来源:Java地带  » 《How To POST JSON Data with PHP cURL》

» 本文章为Java地带整理创作,欢迎转载!转载请注明本文地址,谢谢!
» 部分内容收集整理自网络,如有侵权请联系我删除!

» 订阅本站:https://blog.daoshengtech.cn/feed/

标签: PHP

评论已关闭