简体   繁体   中英

POST HTML FORM data to REST API using PHP cURL

I'm trying to POST data from a HTML form into a REST API, for reference, the API can be found here: Gamification Kinben

The form itself is fairly simple for now as this is a proof of concept at the moment, but on submit I get the following error:

{"content":null,"contentResponseType":"BAD_REQUEST","info":[{"message":": may not be null"},{"message":": may not be null"},{"message":": {API key is not valid}"}]}

HTML FORM

    <form method="post" action="#">
        <input type="text" id="nickname" name="nickname" placeholder="nickname">
        <input type="password" id="password" name="password" placeholder="password">
        <input type="text" id="reference" name="reference" placeholder="ref12345">
        <input type="text" id="roleIds" name="roleIds" placeholder="3">
        <button type="submit" id="submit">Add Player</button>
    </form>

PHP cURL

<?php

//set empty variable placeholders
$nickname = $password = $reference = $roleIds = "";

//Get data from Form
$nickname = secure_data($_POST['nickname']);
$password = secure_data($_POST['password']);
$reference = secure_data($_POST['reference']);
$roleIds = secure_data($_POST['roleIds']);

//Set API Key
$apiKey = "abc123-this-isa-example-ofthekey23124";

//Strip html and slashes etc
function secure_data($data){
    $Sdata = trim($data);
    $Sdata = stripslashes($data);
    $Sdata = htmlspecialchars($data);
    //var_dump($Sdata);
    return $Sdata;
}

//Set up POST array
$array = array (
    "nickname" => $nickname,
    "password" => $password,
    "reference" => $reference,
    "roleIds" => $roleIds,
    "apiKey" => $apiKey,
);

$data_string = json_encode($array);

var_dump ($data_string);

$url = 'serveraddress/gamification_engine/player/';

//Create cURL connection
$curl = curl_init($url);

//set cURL options
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

//Execute cURL
$curl_response = curl_exec($curl);

//Output server response
print_r($curl_response);

//Close cURL connection
curl_close($curl);

?>

As the response says, get a working API key.

{API key is not valid}

您的API密钥无效,或者您没有将其正确发送到API

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