Как передать php массив методом post
Для передачи массива методом POST необходимо использовать функцию http_build_query() .
$data = ['foo' => 'bar', 'baz' => 'boom']; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); // Создаёт и возвращает контекст потока с опциями, указанными в массиве options. $result = file_get_contents('http://example.com/submit.php', false, $context); // Отправляет http-запрос на домен www.example.com с дополнительными заголовкам, показанными выше
Php отправить post массив
В прошлых темах была рассмотрена отправка на сервер отдельных значений. Однако отправка набора значений, то есть массивов в PHP может вызвать некоторые сложности. Рассмотрим, как можно отправить на сервер и соответственно получить на сервере массивы данных.
Например, определим следующий файл users.php :
echo "В массиве " . count($users) . " элементa/ов
"; foreach($users as $user) echo "$user
"; ?>
В данном случае мы предполагаем, что параметр «users», который передается в запросе типа GET, будет представлять массив. И соответствено мы сможем получить из него данные.
Чтобы передать массив этому скрипту, обратимся к нему со следующим запросом:
http://localhost/users.php?users[]=Tom&users[]=Bob&users[]=Sam
Чтобы определить параметр строки запроса как массив, после названия параметра указываются квадраные скобки []. Затем мы можем присвоить некоторое значение: users[]=Tom . И сколько раз подобным образом будет присвоено значений, столько значений и будет в массиве. Все значения, как и обычно, отделяются амперсандом. Так, в данном случае в массив передаются три значения.
Подобным образом мы можем отправлять данные в запросе POST из формы. Например, определим следующий скрипт:
"; foreach($users as $user) echo "$user
"; > ?>Форма ввода данных
User 1:
User 2:
User 3:
Как известно, название ключа передаваемых на сервер данных соответствует значению атрибута name у элемента формы. И чтобы указать, что какое-то поле ввода будет поставлять значение для массива, у атрибут name поля ввода в качестве значения принимает название массива с квадратными скобками:
Соответственно, сколько полей ввода с одним и тем же именем массива мы укажем, столько значений мы сможем передать на сервер. Так, в данном случае на сервер передается три значения в массиве users:
Причем данный принцип применяется и к другим типам полей ввода формы html.
При этом в примерах выше передавался обычный массив, каждый элемент которого в качестве ключа имеет числовой индекс. Соотвенно, используя индекс, мы можем получить определенный элемент массива:
$firstUser = $_POST["users"][0]; echo $firstUser;
Но также мы можем в элементах формы явным образом указать ключи:
$secondUser
$thirdUser"; > ?>Форма ввода данных
User 1:
User 2:
User 3:
Например, первое поле добавляет в массив элемент с ключом «first»
Поэтому на сервере мы можем с помощью данного ключа получить соответствующий элемент:
$firstUser = $_POST["users"]["first"];
How to POST an associative array in PHP
EDIT Is it possible to pass the two values into one associative array BEFORE submission ? I would like to pass it in this form:
Because he said «using only php script». So if he has to post data on this page using only php script so for a beginner i thought cURL would be good.
@HankyPanky — That would be if the server is contacting another server to pull information back to the server. This is client to server to client and back to the server. I don’t know where the cURL would come into the picture.
7 Answers 7
Here is a method using pure HTML that get’s you nearly exactly where you want to be, and only uses HTML:
Which would give you in PHP:
$post_options = array( 'options' => array( 'deptid '=> '[that input element value]', 'deptname' => '[that input element value]' ) );
Which you can then (including sanitizing) access such as this:
$post_options = array('options'); if (is_numeric($post_options['deptid'] && $post_options['deptid'] > 0) < // Do whatever >if (is_string($post_options['deptname'] && strlen($post_options['deptname'] > 2)) < // Do whatever >
Or. You want to reference the deptid in the input name attribute and use it to modify the row for a department name? Which seems to indicate something like this:
The problem with this is that the $deptid value becomes a value that’s not actually directly named or referenced. I think this is potentially problematic to implement due to this abstraction of the value from the server to the client and back, so I would recommend what I have at the top instead. It’s not much of a difference in practice, but it’s more or less self-documenting.
Note, if you wanted to serialize a list of departments, it’s a little trickier. You might, for instance, try this:
Which would add an indexed value for every input . However. They were would not be directly associated. So you would get, instead, two zero-indexed arrays for each key.
What I would suggest in this case is to use Javascript to add each new department’s input elements, so you can give each a number like:
Or do the old-school POSTBACK method and use PHP to count $POST[‘options’] and «manually» add a new «row» of inputs with the same index. It’s a common trap, so you just have to think about it if this is what you’re after at some point.
PHP, pass array through POST
or using implode() to create a single variable, pass the variable and then use explode() to get back the values into a new array?
Please expand on this question. Why do you need to pass the array? What «security» are you looking for? What does the array contain? What is the context of the application? With it as it is now, it’s very vague and won’t get you a good answer.
5 Answers 5
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33); $dataString = serialize($data); //send elsewhere $data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
I was under the impression that you were looking for a way to send the data reliably, not «securely». No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
If I encountered this requirement now, I might attempt to use some form of cryptographic signature to validate the data.
The first comment answers this.
array('first_name'=>'john','last_name'=>'smith'), 1 => array('first_name'=>'jane','last_name'=>'jones'), ) ?>
The name tag can work as an array.
You could put it in the session:
session_start(); $_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
" /> $passed_array = unserialize($_POST['input_name']);
Note that to work with serialized arrays, you need to use POST as the form’s transmission method, as GET has a size limit somewhere around 1024 characters.
I’d use sessions wherever possible.
SESSION is more secure than to store data in input type so SESSION is server side so user can not change it. Agree with you @laxonline
There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).
XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:
The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into < . For example:
Form Modification
If I were on your site, I could use Chrome’s developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.
I could, for example, add extra values to your array, or values that don’t belong in the array. If this were a file system manager, then I could add files that don’t exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php ).
In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn’t safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.
Как передать array через POST?
Важно для меня, чтобы я отправил POST запрос и он уже выполнялся сам, чтобы файл start.php не ждал пока в файле script.php завершит свои действия которые могут выполняться в течении 20-30 секунд).
Как я могу это сделать?
Простой 8 комментариев
Чтобы передать массив его нужно сериализовать. Например в JSON — json_encode($ваш_массив); и передавать соответственно уже эти данные. Можно просто в теле запроса, можно каким-нибудь параметром.
Важно для меня, чтобы я отправил POST запрос и он уже выполнялся сам, чтобы файл start.php не ждал пока в файле script.php завершит свои действия
PHP при любом раскладе будет ждать ответ. Чтобы не блокировать страницу нужно использовать AJAX-запросы из под JS.
Дмитрий Дерепко, так асинхронный код на PHP так же будет ждать выполнения всех запущенных в асинхронности скриптов. Или вы о чем? А на счет форка хз. Честно говоря сам не сталкивался, но слышал, что на длинных запросах, а автор как раз про 20-30 секунд пишет, частенько падает все с ошибками. Хотя может ошибаюсь конечно 🙁
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
Вот так отправил POST запрос, а как его принять?)
Хотел записать в файл:
file_put_contents(__DIR__ . '/logs/tester.txt', $_POST . PHP_EOL, FILE_APPEND);
— в результате получаю запись: Array
пытался json_decode(_POST) результат не лучше.
Us59, вы отправляете JSON в теле запроса. Чтобы его принять в данном случае нужно считывать его с потока php://
file_put_contents(__DIR__ . '/logs/tester.txt', file_get_contents('php://input') . PHP_EOL, FILE_APPEND);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['json' => json_encode($data)]));
file_put_contents(__DIR__ . '/logs/tester.txt', $_POST['json'] . PHP_EOL, FILE_APPEND);
// Input $data = extract($_POST); // Output $url = 'http://api.example.com'; $data = array('foo' => 'bar'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $result = curl_exec($ch); curl_close($ch);
Можно использовать параметры CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUT, чтобы автоматически разрывать соединение. При отправке запроса будет ошибка, но запрос выполнится:
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
По хорошему, нужно использовать очередь сообщений. Так же можно попробовать запустить процесс в фоновом режиме:
Как правильно запустить внешний скрипт в фоновом режиме?
Еще, как вариант, Вы можете сбросить соединение на стороне script.php без остановки скрипта, если на сервере используется FastCGI (FPM):
function wbAuthPostContents($url, $post=null, $username=null,$password=null) < if (func_num_args()==3) < $password=$username; $username=$get; $post=array(); >if (!is_array($post)) $post=(array)$post; $cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password") ); $post=http_build_query($post); $opts = array( 'http'=>array( 'method'=>'POST', 'header'=>$cred, 'content'=>$post ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); return $result; >