1
\$\begingroup\$

Fairly new to writing PHP. I want some PHP code to query an API with a post request, set specific headers and message body, and echo out the JSON response. This is the code I have come up with, which validates but I dont know if its optimal:

<?php
$url = 'http://api.local/rest/users';
$data = '{"4":"four","8":"eight"}';
$accesstoken = 'abc';
$apikey = 'abc';
$companyid = 'abc';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer $accesstoken', 'x-api-key: $apikey', 'x-proxy-global-company-id: $companyid']);
$result = curl_exec($ch);
?>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.