B
B
BlueNorp2019-10-30 10:34:15
PHP
BlueNorp, 2019-10-30 10:34:15

Returns NULL in $_POST request when there is a captcha and 2 files are selected for upload, why?

There is a form:

<form action="send_msg.php" enctype="multipart/form-data" method="POST">
<input type="text" name="email" required></br>
<textarea name="body" required></textarea></br>
<input type="file" name="file[]" multiple style="margin-bottom: 5px;"></br>
<div style="transform:scale(0.8); transform-origin:0; margin-left: 68px;" class="g-recaptcha" data-sitekey="MY_KEY" data-callback="captcha_onclick"></div>
<input type="submit" name="gsubmit" value="Отправить"></br>
</form>

And there is the processing code:
if (isset($_POST['g-recaptcha-response'])) $captcha_response = $_POST['g-recaptcha-response'];
else $captcha_response = $_POST['recaptcha'];
 
$url = 'https://www.google.com/recaptcha/api/siteverify';
$params = [
    'secret' => 'KEY',
    'response' => $captcha_response,
    'remoteip' => $_SERVER['REMOTE_ADDR']
];
 
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
$response = curl_exec($ch);
if(!empty($response)) $decoded_response = json_decode($response);
 
$success = false;
 
if ($decoded_response && $decoded_response->success)
{
    $success = $decoded_response->success;
}
 
$result = $success ? 'Капча пройдена успешно!' : 'Неверная капча!';
echo $result;

So, when sending without files, the captcha passes, like the whole form, but if you add two pictures, the entire POST request becomes null, what should I do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Ninazu, 2019-10-30
@BlueNorp

I recommend starting with a working example, and then complicating it with captchas and other logic

<?php
if ($_POST) {
  die(json_encode([$_POST, $_FILES]));
}
?>

<form enctype="multipart/form-data" method="POST">
  <input type="text" name="name" required></br>
  <input type="file" name="file[]" multiple style="margin-bottom: 5px;">
  <input type="submit" name="gsubmit" value="Отправить"></br>
</form>
<script>
  document.querySelector("form").addEventListener("submit", function(e) {
    let form = e.target;
    e.preventDefault();
    e.stopImmediatePropagation();
    let xhr = new XMLHttpRequest();

    xhr.open(form.method, form.action);
    xhr.onreadystatechange = function(result) {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let responseData = JSON.parse(xhr.responseText);
        console.log(responseData);
      }
    };

    xhr.send(new FormData(form));
  }, true);
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question