Sobes.tech
Junior — Middle

How can a hidden field be added when sending data to a REST API?

sobes.tech AI

Answer from AI

To add a hidden field when sending data to a REST API in PHP, you can include an additional parameter in the request body that is not visible to the user but is sent to the server.

If it's an HTML form, you can use <input type="hidden">:

<form method="POST" action="/api/endpoint">
  <input type="hidden" name="secretField" value="secretValue">
  <input type="text" name="username">
  <input type="submit" value="Send">
</form>

If the data is sent via PHP using cURL or another HTTP client, simply add the required field to the data array:

$data = [
    'username' => 'user123',
    'secretField' => 'secretValue'
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ],
];
$context  = stream_context_create($options);
$result = file_get_contents('https://example.com/api/endpoint', false, $context);

Thus, the hidden field is transmitted along with the other data but is not visible to the user.

How can a hidden field be added when sending data to… - sobes.tech