Как получить содержимое POST на php?
Я отправляю POST на страницу php следующее:
Это тело запроса (запрос POST).
Что мне нужно сделать в php, чтобы извлечь это значение?
var_dump($_POST);
Этот код не работает.
Ответ 1
Чтобы получить доступ к содержимому объекта запроса POST или PUT (или любого другого метода HTTP):
$entityBody = file_get_contents(‘php://input’);
Кроме того, STDIN константа — это уже открытый поток php://input , поэтому вы можете в качестве альтернативы сделать:
$entityBody = stream_get_contents(STDIN);
Из документации PHP по потокам ввода-вывода :
php: // input — это поток только для чтения, который позволяет вам читать необработанные данные из содержимого запроса. В случае запросов POST предпочтительнее использовать запрос php: // вместо того, чтобы использовать $HTTP_RAW_POST_DATA, который зависит от специальных директив php.ini. Более того, для тех случаев, когда $HTTP_RAW_POST_DATA не устанавливается по умолчанию, это потенциально менее ресурсоемкая альтернатива установки .
always_populate_raw_post_data. php: // ввод недоступен с enctype = «multipart/form-data».
В этом случае, если поток php://input , к которому вы обращаетесь как веб-SAPI, будет недоступен для поиска . Это означает, что его можно прочитать только один раз. Если вы работаете в среде, где регулярно загружается содержимое HTTP, вы можете сохранить ввод в его потоковой форме (а не буферизовать его).
Для реализации потокового ресурса можно выполнить что-то вроде этого:
function detectRequestBody()
$rawInput = fopen(‘php://input’, ‘r’);
$tempStream = fopen(‘php://temp’, ‘r+’);
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
>
php://temp позволяет вам управлять потреблением памяти, потому что это прозрачно переключается на хранилище файловой системы после сохранения определенного количества данных (по умолчанию 2M). Этим размером можно управлять в файле php.ini или добавляя /maxmemory:NN , где NN — это максимальный объем данных в байтах, которые необходимо сохранить в памяти перед использованием временного файла.
Конечно, если у вас нет действительно веской причины для поиска во входном потоке, вам не понадобится эта функция в веб-приложении. Обычно достаточно одного чтения содержимого объекта HTTP-запроса – нет необходимости заставлять клиентов ждать долгое время для выяснения, что делает в а ше приложение.
Обратите внимание, что ввод php: // недоступен для запросов с указанием заголовка « Content-Type: multipart/form-data ( enctype=»multipart/form-data» в HTML-формах)». Это происходит из-за того, что интер прет атор PHP уже проанализировал данные формы в $_POST .
Ответ 2
Возможное решение:
function getPost()
if(!empty($_POST))
// когда в качестве HTTP Content-Type в запросе используется application/x-www-form-urlencoded или multipart/form-data
// ПРИМЕЧАНИЕ: если это так и $_POST пуст, можно проверить порядок переменных (variables_order) в php.ini! — они должны содержать букву P
return $_POST;
>
// при использовании application/json в качестве HTTP Content-Type в запросе
$post = json_decode(file_get_contents(‘php://input’), true);
if(json_last_error() == JSON_ERROR_NONE)
return $post;
>
return [];
>
print_r(getPost());
Ответ 3
Этот пример о том, как создать PHP API с file_get_contents(«php://input») , и об использовании с javascript в связке с ajax XMLHttpRequest .
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
if (this.readyState == 4 && this.status == 200)
console.log(«done»);
>
>
>;
xhttp.open(«POST», «http://127.0.0.1:8000/api.php», true);
xhttp.send(JSON.stringify(
username: $(this).val(),
email:email,
password:password
>));
$data = json_decode(file_get_contents(«php://input»));
$username = $data->username;
$email = $data->email;
$password = $data->password;
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
How to get all post data php
Solution 1: That’s because contents of sent by GET/POST methods from HTML to PHP are stored inside the superglobal variable and not (unless you don’t define property of the tag as , which then causes the filename to be passed as a string to GET/POST). in an array Solution 2: Solution 3: for current GET query for any array in your case Solution: With that many checkboxes, if there are other inputs on your form you may be exceeding PHP’s setting.
I can get all $_POST data except for one
That’s because contents of input type=file sent by GET/POST methods from HTML to PHP are stored inside the superglobal variable $_FILES and not $_POST (unless you don’t define enctype property of the form tag as «multipart/form-data» , which then causes the filename to be passed as a string to GET/POST).
If you var_dump($_FILES) / print_r($_FILES) you’ll see an array like this:
Array ( [file] => Array ( [name] => test.pdf [type] => application/pdf [tmp_name] => C:\Windows\Temp\php1485.tmp [error] => 0 [size] => 1073054 ) )
OBS: be sure to have enctype=»multipart/form-data» as property of your form and file_uploads set to on in your php.ini file.
public function update()< $first_name = $this->input->post('inputFirstName'); $last_name = $this->input->post('inputLastName'); $contact_number = $this->input->post('inputContactNumber'); $address = $this->input->post('inputAddress'); $email_address = $this->input->post('inputEmailAddress'); //$image_url = $this->input->post('inputPicture'); $image_url = $_FILES['inputPicture']; $id = $this->input->post('inputID'); var_dump($_POST);exit; $this->form_validation->set_rules('inputFirstName', 'First Name', 'required|max_length[35]'); $this->form_validation->set_rules('inputLastName', 'Last Name', 'required|max_length[35]'); $this->form_validation->set_rules('inputContactNumber', 'Contact Number', 'required|exact_length[11]|numeric'); $this->form_validation->set_rules('inputAddress', 'Address', 'required|min_length[5]|max_length[255]'); $this->form_validation->set_rules('inputEmailAddress', 'Email Address', 'required|min_length[10]|max_length[255]|valid_email'); if($this->form_validation->run() == FALSE)< $data['title'] = 'Address Book'; $data['contacts_info'] = $this->contacts_model->getContacts(); $this->load->view('home', $data); redirect(); > else< if(!isset($_FILES['inputPicture']))< $this->contacts_model->updateContactNoPic($id, $first_name, $last_name, $contact_number, $address, $email_address); > else< $image = 'assets/images/' . $image_url; $this->contacts_model->updateContact($id, $first_name, $last_name, $contact_number, $address, $email_address, $image); > $data['title'] = 'Address Book'; $data['contacts_info'] = $this->contacts_model->getContacts(); $this->load->view('home', $data); redirect(); >
How to get body of a POST in php?, php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to
How to Get Data from a Request
This PHP tutorial will show you how to get data from a request. We will look at examples of Duration: 19:22
How can I get all posted data as one single line in php?
I don’t quite understand what you want, but I think you’re looking for the following:
$raw_data = file_get_contents("php://input");
$array_data = $_POST // this is already an array?
echo $_SERVER[‘QUERY_STRING’] for current GET query
http_build_query for any array
in your case http_build_query($_POST)
How can i run PHP Preg_match against all POST Data?, I have a HTML form where users submit information, depending how many options the user selects in a form there is a different number of POST
POST not sending all data
With that many checkboxes, if there are other inputs on your form you may be exceeding PHP’s max_input_vars setting. The PHP manual defines this setting as:
How many input variables may be accepted (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
You can fix this by increasing that setting in your php.ini, or reducing the number of inputs in your form to fit the limit.
Get all POST data and send in email, foreach ($_POST as $key => $value) $message .= «Field «.htmlspecialchars($key).» is «.htmlspecialchars($value).
How can i run PHP Preg_match against all POST Data?
You could use array_walk_recursive to iterate over the entire $_POST array, testing each value with your preg_match code:
array_walk_recursive($_POST, function ($v) < if (preg_match('/[\'^£$%&*()><>,|=_+¬-]/', $v) || preg_match("/\\s/", $v)) < exit("Illegal characters found"); >>);
How to get All input of POST in Laravel, There seems to be a major mistake in almost all the current answers in that they show BOTH GET and POST data