PHP Simulates post Submitting json Data Sample Based on curl

  • 2021-10-24 19:07:55
  • OfStack

This article illustrates how PHP submits json data based on curl simulating post. Share it for your reference, as follows:

Here, the key of php simulating post submitting json data operation is to set in the header Content-Type


<?php
header("Content-type:application/json;charset=utf-8");
$url="http://192.168.10.234:8080/uc/login/loginid";
$param=array(
  // Registration field 
  "name"=>"test001",
  "pass"=>"xxxx",
);
$data = json_encode($param);
list($return_code, $return_content) = http_post_data($url, $data);//return_code Yes http Status code 
print_r($return_content);exit;
function http_post_data($url, $data_string) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json; charset=utf-8",
    "Content-Length: " . strlen($data_string))
  );
  ob_start();
  curl_exec($ch);
  $return_content = ob_get_contents();
  ob_end_clean();
  $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  return array($return_code, $return_content);
}

PS: Here we recommend several practical json online tools for your reference:

Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json

JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON Interconversion Tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tool:
http://tools.ofstack.com/code/jsoncodeformat

C Language Style/HTML/CSS/json Code Formatting and Beautification Tool:
http://tools.ofstack.com/code/ccode_html_css_json

For more readers interested in PHP related contents, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial" and "json Format Data Operation Skills Summary in PHP"

I hope this article is helpful to everyone's PHP programming.


Related articles: