Skip to content

Instantly share code, notes, and snippets.

@moalex
Last active December 9, 2017 02:37
Show Gist options
  • Save moalex/3028d9ee69e0e02afbc3b60d4458c79e to your computer and use it in GitHub Desktop.
Save moalex/3028d9ee69e0e02afbc3b60d4458c79e to your computer and use it in GitHub Desktop.

PHP - POST JSON Data with cURL

<?php
$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   
                                                                                                                     
$ch = curl_init('http://api.local/rest/users');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   
                                                                                                                     
$result = curl_exec($ch); 
?>

Gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment