Home » Php » Get response from php script with curl after posting response

Get response from php script with curl after posting response

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a form which uses curl to submit the apiKey to my server and then the script on my server verify the key and returns true and false. but instead of response. I’m getting Trying to access array offset on value of type null. I want to know How to get response from my server after curl submission.

Curl Submit

    $post['apiKey'] = $apiKey;    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

     $json = curl_exec($ch);
     $response = json_decode($json, true);

Server Script

<?php 

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

$postParams = allowedPOSTParams($allowed_params=['apiKey']);

if (!isset($postParams['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($postParams['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}

Allowed Post Params Function:

function allowedPOSTParams($allowed_params=[]) {
    $allowed_array = [];
    foreach ($allowed_params as $param) {
        if (isset($_POST[$param])) {
            $allowed_array[$param] = $_POST[$param];
        } else {
            $allowed_array[$param] = NULL;
        }
    }
    return $allowed_array;
}
How to&Answers:

Replace

curl_setopt($ch, CURLOPT_POSTFIELDS, $apiKey);

with

curl_setopt($ch, CURLOPT_POSTFIELDS, array('apiKey'=>$apiKey));

Then, you will able to find apiKey as POST parameter.