php curl post json request code example

Example 1: curl post json

curl -X POST -H "Content-Type: application/json" \
 -d '{"username":"abc","password":"abc"}' \
 https://api.example.com/v2/login

Example 2: http post request php curl

$post = [
   'teste' => $_POST['teste']
];
httpPost('url.com', $post);
// function
function httpPost($url, $data)
{
   	$curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

Example 3: how to do a post with json body curl php

// API URL$url = 'http://www.example.com/api';// Create a new cURL resource$ch = curl_init($url);// Setup request to send json via POST$data = array(    'username' => 'codexworld',    'password' => '123456');$payload = json_encode(array("user" => $data));// Attach encoded JSON string to the POST fieldscurl_setopt($ch, CURLOPT_POSTFIELDS, $payload);// Set the content type to application/jsoncurl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));// Return response instead of outputtingcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Execute the POST request$result = curl_exec($ch);// Close cURL resourcecurl_close($ch);

Tags:

Php Example