1

I make a PHP CURL PUT JSON request with basic AUTH via API:

$data = <<<JSON
  {
    "name": "John",
    "age": "32",
    "address": {
                 "city": "London",
                 "street": "Laxin street 32",
                 "zip": "32567"
               }    
   } JSON;

Here is what I have:

$data_json = json_encode($data);
$url = "https://www.website.com/record?apiKey={API_KEY}";
$username = "user";
$password = "123abcd"; 
$encodedAuth = base64_encode($username.":".$password);
$curl = curl_init();
        curl_setopt_array($curl, [CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "PUT",
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER => array("Authentication : Basic ".$encodedAuth),
        CURLOPT_USERPWD => $username.":".$password,
        CURLOPT_HTTPAUTH => CURLAUTH_ANY,
        CURLOPT_POSTFIELDS => $data_json,
        CURLOPT_HTTPHEADER => [
        "Cache-Control: no-cache",
        "Content-Type: application/json",
        "TOKEN: SAMPLE_TOKEN"],]);
        $response = curl_exec($curl);    
        curl_close($curl);

In response, I got the original record data without changes that I sent via API.

How can I request that PUT using PHP's curl with basic auth? I tried some answers to similar questions but with no success.

5
  • What is the actual API hostname? What is the response status code? Commented Nov 12, 2023 at 22:53
  • 1
    quick questions why do you have 2 CURLOPT_HTTPHEADER? one is overwriting the other. Also why JSON like you posted and why not a php array and then json_encode it, there must be a problem with they way you are defining the JSON. Also if you are setting authentication header then whyCURLOPT_USERPWD and CURLOPT_HTTPAUTH ? Commented Nov 12, 2023 at 23:22
  • Hi Adi, Can you provide an example for "Also why JSON like you posted and why not a php array and then json_encode it, there must be a problem with they way you are defining the JSON"? Commented Nov 13, 2023 at 5:17
  • Ok, Adi, I sent JSON because I already have JSON and only need to add it additional data. Commented Nov 13, 2023 at 16:59
  • You are right I got back slashes: "\"{\\r\\n \\\"name\\\": \\\"John\\\",\\r\\n \\\"age\\\": \\\"32\\\",\\r\\n \\\"address\\\": {\\r\\n \\\"city\\\": \\\"London\\\",\\r\\n \\\"street\\\": \\\"Laxin street 32\\\",\\r\\n \\\"zip\\\": \\\"32567\\\"\\r\\n } \\r\\n } \"" Commented Nov 13, 2023 at 21:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.