简体   繁体   中英

PHP file not receiving JSON via CURL

I have a project where I have to send exam data with exam-name and the selected number of questions from the list:

  • I have to send JSON via AJAX to my make_exam.php file
  • questions.php file sends data to backend.php via CURL
  • above is the project architecture I have to follow

  • for testing, the backend.php is just sending JSON it receives. But looks like it is receiving nothing.

    var exam_json = {"action":"exam_created","exam_name":"test- 1","questions[2,5,9]}

     var str_json = "exam="+(JSON.stringify(exam_json)); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; xhttp.open("POST", "functions.php", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send(str_json); 

CURL from make_test.php:

<?php


        $json = $_POST["exam"];
        $exam_json = json_encode($json);
        //if I echo $exam_json, it will display correctly meaning I am getting data here
        $ch = curl_init();

        $curlConfig = array(
            CURLOPT_URL =>"backend.php",
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_POSTFIELDS     => $exam_json,
            CURLOPT_HTTPHEADER     => array( 
                                    'Content-Type: application/json', 
                                    'Content-Length: ' . strlen($exam_json)),
        );
        curl_setopt_array($ch, $curlConfig);
        $result_back = curl_exec($ch);
        echo $result_back;

?>

backend.php receives data sent from make_exam.php via CURL:

<?php

    $data_test = json_decode(file_get_contents('php://input'), true);

    echo $data_test;
    //the echo is always empty
?>

method 1:

for post json in body of http you must use stipslash

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url ,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\n\t\"a\":1,\n\t\"b\":5\n}",
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

method 2:

post JSON array using curl

method 3 :

use Guzzle

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']
]);

read more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM