简体   繁体   中英

PHP Post Request (CURL, JSON) not Working

I come humbly before great developers with this issue of mine. Sending a post request in JSON format to Firebase. Here's my code

$token = $_SESSION['token'];
$data = array(
    'id' => 156,
    'quizName' => $quizName,
    'numberOfQuestions' => $numberOfQuestions, 
    'isTimed' => true,                         
    'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
    'targetedClass' => 'Js One',
    'subject' => $subject_name,
    'schoolLevel' => $schoolLevel,
    'questions' => array('question' => $question, 'questionMark' => $marks, 
        'options' => array('option' => 'A', 'answer'=> $optionA, 'option' => 'B', 'answer'=> $optionB, 'option' => 'C', 'answer' => $optionC, 'option' => 'D', 'answer' => $optionD, 'option' => 'E', 'answer' => $optionE),
        'hasImage' => true,
        'images' => array('images-1' => 'image-1', 'images-2' => 'image-2'),
        'correctionOption' => $correct_option
    ),
    'totalValidMarks' => $totalValidMarks,
    'validUntil' => $validUntil
);

// API URL
$url = ' ';
// Create a new cURL resource
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('x-access-token:'.$token, 'Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.

echo "<pre>$result.</pre>";

But I'm receiving an error:

"details":[{"message":"\"id\" is required","path":["id"],"type":"any.required","context":{"label":"id","key":"id"}}]}

Please try sending like this:

    $params = $myDataArray;
    $data_string = json_encode($params);
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $toEndPoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HTTPHEADER => array(
            "x-access-token: $token",
            "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;
    }
    exit;

@godlovesme, to answer for your latest comment:

I don't really like using While loops as they can easily let you fall in an endless loop, but you get what you ask for:

$i = 0;
$questionsArrFormatted = [];
while ($i < count($questionsArr)) {
    $hasImage = count($questionsArr[$i]['question']) ? true : false;
    $questionsArrFormatted[$i] = [
        'question' => $questionsArr[$i]['question'],
        'questionMark' => $questionsArr[$i]['marks'],
        'options' => $questionsArr[$i]['options'], // options should be an array formatted like in your question
        'hasImage' => $hasImage,
        'images' => $questionsArr[$i]['images'],
        'correctionOption' => $questionsArr[$i]['correct_answer']
    ];
    $i++;
}

$data = array(
    'id' => 156,
    'quizName' => $quizName,
    'numberOfQuestions' => $numberOfQuestions,
    'isTimed' => true,
    'numberOfMinutesToComplete' => $numberOfMinutesToComplete,
    'targetedClass' => 'Js One',
    'subject' => $subject_name,
    'schoolLevel' => $schoolLevel,
    'questions' => $questionsArrFormatted,
    'totalValidMarks' => $totalValidMarks,
    'validUntil' => $validUntil
);

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