G
G
Gleb2021-05-16 21:51:04
AJAX
Gleb, 2021-05-16 21:51:04

How to submit form data via cURL?

I tried in various ways to transfer data from the form to the site (api) via curl, but apparently I don’t understand something in this library, although there are a lot of examples on the Internet. Can you suggest how to send them? Thanks in advance <3

Form code:

<div id="popup1" class="mfp-hide popup">
        <h2 class="popup-title">Справка о периоде обучения</h2>
        <form class="reference-form" action="">
            <div class="reference-select">
                <select class="groups" name="groups" id="groups">
                    <option value="default" disabled selected>Выберите группу</option>
                    <?php
                    $groups = loadGroups();
                    foreach($groups as $group){
                    ?>
                    <option id="<?=$group['id']?>" value="<?=$group['id']?>"><?=$group['name']?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="reference-select">
                <select class="obiturients" name="obiturients" id="obiturients">
                    <option value="default" disabled selected>ФИО</option>
                </select>
            </div>
            <button class="reference-btn">Создать</button>
        </form>
    </div>

```

ajax code
$(function () {
    $('.reference-link').magnificPopup();
    $('.groups').change(function () {
    let gid = $(this).val();
    let form = $(this).closest('form');
    $.ajax({
        url: 'data.php',
        method: 'post',
        data: {gid: gid}
    }).done(function (obiturient) {
        console.log(obiturient);
        obiturient = JSON.parse(obiturient);
        form.find('[name="obiturients"]').empty();
        obiturient.forEach(function (obiturient) {
            form.find('[name="obiturients"]').append('<option value='+ obiturient.id +'>' + obiturient.O_fam + ' ' +  obiturient.O_name + ' ' + obiturient.O_otch + '</option>')
        })
    })

})

})


```
You need to pass exactly data.php
append('<option value='+ obiturient.id +'>
<?php
require_once 'db.php';
if (isset($_POST['gid'])) {
    global $obiturient;
    $connection = new mysqli('localhost', 'root', 'root', 'rups');
    $stmt = $connection->query("SELECT * FROM `obiturient` WHERE `group_id`= " . $_POST['gid']);
    $obiturient = $stmt->fetch_all(MYSQLI_ASSOC);
    echo json_encode($obiturient);
}
function loadGroups(){
    global $groups;
    $connection = new mysqli('localhost', 'root', 'root', 'rups');
    $stmt = $connection->query("SELECT * FROM `groups`");
    $groups = $stmt->fetch_all(MYSQLI_ASSOC);
    return $groups;
}

```

cURL itself:
$curl = curl_init(); //инициализация сеанса
curl_setopt($curl, CURLOPT_URL, 'http://diplom/example.php'); //урл сайта к которому обращаемся
curl_setopt($curl, CURLOPT_HEADER, 1); //выводим заголовки
curl_setopt($curl, CURLOPT_POST, 1); //передача данных методом POST
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //теперь curl вернет нам ответ, а не выведет
curl_setopt($curl, CURLOPT_POSTFIELDS, //тут переменные которые будут переданы методом POST
array (
'obiturients'=>$_POST['obiturients'],
));
curl_setopt($curl, CURLOPT_USERAGENT, 'MSIE 5'); //эта строчка как-бы говорит: "я не скрипт, я IE5" :)
curl_setopt ($curl, CURLOPT_REFERER, "http://ya.ru"); //а вдруг там проверяют наличие рефера
$res = curl_exec($curl);

curl_close($curl);

from the second box of the form , but I could not pull out the value using examples from the Internet and send this value. Thanks again in advance for your help.

Screenshot of what we get when sending:

60a16991ad609333924694.jpeg

Well, and most importantly, I don’t understand whether the data is sent at all through cURl, or not? Thank you all for your reply and help in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-05-17
@zkrvndm

If you just need to submit a form from your site to some other site, do this.
Create a test.php file with the following content:

Click here to expand hidden text
<?php

// Указываем браузеру, что ответ будет текстом:
header('Content-Type: text/plain; charset=utf-8');

// Включаем показ ошибок:

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Если это POST-запрос:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  // Адрес для пересылки формы:
  $url = 'http://diplom/example.php';

  // Конвертируем все полученные данные с формы
  // в строку application/x-www-form-urlencoded:

  $vars = http_build_query($_POST);

  // Создаём новый сеанс:
  $curl = curl_init();

  // Указываем адрес целевой страницы:
  curl_setopt($curl, CURLOPT_URL, $url);

  // О отключаем проверку SSL сертификата:
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

  // Устанавливаем заголовки для имитации браузера:

  $headers = array(
    'Accept: */*',
    'Accept-Encoding: identify',
    'Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
    'Connection: keep-alive',
    'Content-Length: '.strlen($vars),
    'Content-Type: application/x-www-form-urlencoded',
    'Host: '.parse_url($url)['host'],
    'Origin: '.parse_url($url)['scheme'].'://'.parse_url($url)['host'],
    'Referer: '.parse_url($url)['scheme'].'://'.parse_url($url)['host'].'/',
    'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
    'sec-ch-ua-mobile: ?0',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: cross-site',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
  );

  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

  // Указываем, что у нас POST запрос:
  curl_setopt($curl, CURLOPT_POST, 1);

  // Разрешаем переадресацию:
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

  // Запрещаем прямяой вывод результата запроса:
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

  // Добавляем данные для отправки:
  curl_setopt($curl, CURLOPT_POSTFIELDS, $vars);

  // Делаем сам запрос:
  $result = curl_exec($curl);

  // Завершаем сеанс:
  curl_close($curl);

  // Выводим результат:
  echo $result;

}

Next, send your form to this test.php file and the php script inside it will send the form to where you specified.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question