0

I found some examples about post and get methods using curl, but I am not able to deal with the server internal error 500. The google console reports error 500 of fetch type. I checked my php configuration and seems to be ok. Context: function in functions.php of a wordpress installation based on elementor template. Ionos hosting. How can I debug this issue?

      $url = 'https://myurl.com/';
    
      $fields = array('var1' => 'value1', 'var2' => 'value2');
      $headers = array('X-MY-TOKEN: tokenValue', 'Content-Type: application/json');
    
      $fields_json = json.encode($fields);
      
      //open connection
      $ch = curl_init();
    
      //setup
      curl_setopt($ch,CURLOPT_URL, $url);
      curl_setopt($ch,CURLOPT_POST, 1);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_json);
      curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
    
      //execute post
      $response = curl_exec($ch);

enter image description here

Update:the php log error shows: PHP Fatal error: Uncaught Error: Call to undefined function encode() How to send then a POST with application/json content-type?

Jaume
  • 3,672
  • 19
  • 60
  • 119
  • https://stackoverflow.com/questions/2687730/how-can-i-make-php-display-the-error-instead-of-giving-me-500-internal-server-er – Don't Panic Dec 27 '21 at 06:27
  • aha, thanks, I activated the logs and seems the error comes from json.encode() method, that is not recognized – Jaume Dec 27 '21 at 06:58
  • https://www.php.net/manual/en/function.json-encode.php – Don't Panic Dec 27 '21 at 07:20
  • Does this answer your question? [How to POST JSON Data With PHP cURL?](https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl) – Don't Panic Dec 27 '21 at 07:22

1 Answers1

1

Base on the error thrown by the server, the function encode() can't find/doesn't exist which returns a 500 error code. I assume you mistype the json_encode().

So it should be:

$fields_json = json_encode($fields);

From the docs. https://www.php.net/manual/en/function.json-encode.php

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 27 '21 at 07:42
  • ohh my mistake... It's working, thanks! – Jaume Dec 28 '21 at 12:30