I have a form where user puts his apiKey then that after checking for errors if everything is good the processing script post the key via curl to my server for verification. then my server should return success true | false and error code if false. but when I send the file the curl response is empty.
$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);
$res = curl_exec($ch);
if ($res === FALSE) {
echo "Curl Error:" . curl_error($ch);
}
curl_close($ch);
print_r($res);
Script we are submitting to:
<?php
define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");
require("includes/initialize.php");
if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");
if (!isset($_POST['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");
$apiKey = escape($_POST['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);
}
You have to send as output the $response
not return
it:
instead of
return json_encode($response);
use
echo json_encode($response);
Also note that if eihter isInputEmpty($apiKey)
or !$apiKey == 25
evaluate true then execution does not enther the last conditional block and you won't have any output in the body of the response.
The script logic is that for some kind of errors a specific header is set to notify the error.
The curl script that send the request should inspect headers too.
To do so you may use the following code to be placed before curl_exec
$response_headers = [];
curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
function( $curl, $header ) use ( &$response_headers )
{
$len = strlen( $header );
$header = explode(':', $header, 2);
if( count( $header ) < 2 ) { return $len; } // ignore invalid headers
$response_headers[ strtolower( trim( $header[0] ) ) ] = trim( $header[1] );
return $len;
}
);