1

I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.

Here is the php:

<?php
    $post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);

    $transfer = json_encode($post);   


    $ctrl = curl_init();
    curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
    curl_setopt($ctrl, CURLOPT_POST, TRUE);
    curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
    curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
    $response = curl_exec($ctrl);
    curl_close($ctrl);
    $response = json_decode($response);

    echo $response;
?>

If I were to echo $transfer it would read:

{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
             "output":"4"}
}

I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:

{"message":"An unknown internal error occured","success":false}

How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?

1 Answers1

2

Try setting the header to say you are sending JSON...

curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($transfer))                                                                       
); 

For the HTTPS, you may also need...

curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);

You also may try...

curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1); 
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thanks but didn't work. My script seems to be dying before I send a request out. So it def something with my curl methods – connor.roche Mar 08 '18 at 17:20
  • Not sure if your still having problems, but added something which helps when using https. – Nigel Ren Mar 08 '18 at 19:19
  • @connor.roche Remove the `CURLOPT_POSTFIELDS` line if you are going to send as json content type. That may be the cause of your script crater. – IncredibleHat Mar 08 '18 at 19:30