Производство фотообоев в Новосибирске. Интернет магазин фотообоев. Изготовление - один день! Каталог 10 000 изображений!
8 Ноябрь 2018

PHP — как отправить файл POST запросом cURL

posted in PHP, Полезности, Программирование |

Собственно, задача — автоматизация процесса загрузки файла на сайты через веб-форму.
То есть на разные сайты мне нужно загрузить один и тот же файлик — захожу на сайт, выбираю нужный файл жму аплоад!
Список адресов сайтов с формой есть, файл конечно тоже — нужно автоматизировать!

Для реализации поставленной задачи решил использовать библиотеку curl, но вот с передачей файла возникла проблема — никак у меня не получалось отправить файл в форму!
Довольно долго рыл и нарыл таки рабочее решение
https://stackoverflow.com/questions/4223977/send-file-via-curl-from-form-post-in-php и оно же на другом ресурсе
https://exceptionshub.com/send-file-via-curl-from-form-post-in-php.html

Собственно, чел видимо затрахался как и я и решил передаваемые в POST данные сгенерировать самостоятельно с правильными заголовками.
Незнаю почему, но у меня в кодировке base64 ну никак не передавался, вернее передавался, но в такой кодировке и сохранялся 🙂 т.е. в закодированном виде, поэтому я несколько переделал скрипт до рабочего состояния (и увеличил кол-во передаваемых переменных для наглядности).

Получился такой код


public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY.= 'Content-Disposition: form-data; name="sometext1"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY.= "Some Data1" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="sometext2"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY.= "Some Data2" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 3nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: 8bit' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= file_get_contents($file_url) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}

PS
Если на сайте разрешить сохранение php файлов — фактически получаем возможность удалённого управления множеством сайтов!
Пишется скрипт-сценарий, собственно, что именно нужно сделать на сайте.
Далее в автоматическом режиме (с помощью вышеуказанного кода) его загружаем (на все сайты) и его же «дёргаем» — соответственно он на стороне сайта выполняется веб сервером!

Оставить комментарий