Search code examples
phpcurlphp-curl

PHP Curl does not work when I pass a variable


<?php
class Updater {

  function addTextOnImage($id,$text_on_image){
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://example.com/example/items/message/".$id,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "PATCH",
       CURLOPT_POSTFIELDS =>"{\"text_on_image\": \"".$text_on_image."\"}",
      CURLOPT_HTTPHEADER => array(
        "Authorization: Bearer token",
        "Content-Type: application/json",
        "Cookie: PHPSESSID=ssid"
      ),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
  }

}

I execute the addTextOnImage Function.

If i execute it like:

$value= "A test string";
$updater->addTextOnImage($id,$value);

It works. But if I do it like this:

$value= strval($result);
$updater->addTextOnImage($id,$value);

I get an Empty or Wrong Paylodad exception. A var_dump pf the $value (in the second version, which doesn't work) looks like:

sring(68) "IF ANIMALS CAN DO IT"

So both are strings, why it doesn't work with the second one?


Solution

  • I found a solution:

    $data = array(
          'text_on_image' => $text_on_image
        );
    $payload = json_encode($data);