phpcurl

Please help php form post $_POST & showing in curl


Hi Hope someone can help. I have a little API script

I'm trying to post from a form on the same page ACTIVE or SUSPENDED.

But show text in the curl script. but its not showing $variable and just the code I put in

<?php
$variable = $_POST['name'];
echo $variable;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '....');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'accept: application/json',
    'Content-Type: application/json',
    'Authorization: Bearer ...',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "state": "<?php echo $variable; ?>"}');

$response = curl_exec($ch);

print_r($response);

curl_close($ch);

?>

<form method="POST" action="suspend.php">
    <input type="text" name='name' value="some value">
    <button type="submit">Go</button>
</form>


Solution

  • <?php echo doesn't work inside a string. It only works after you've exited PHP mode with ?>.

    Create an array containing the variable and use json_encode().

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["state" => $variable]));