METANIT.COM

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.

Читайте также:  Encrypted and encrypt php

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.

Источник

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 . И сколько раз подобным образом будет присвоено значений, столько значений и будет в массиве. Все значения, как и обычно, отделяются амперсандом. Так, в данном случае в массив передаются три значения.

Передача массивов в PHP на сервер в запросе GET

Подобным образом мы можем отправлять данные в запросе POST из формы. Например, определим следующий скрипт:

     "; foreach($users as $user) echo "$user
"; > ?>

Форма ввода данных

User 1:

User 2:

User 3:

Как известно, название ключа передаваемых на сервер данных соответствует значению атрибута name у элемента формы. И чтобы указать, что какое-то поле ввода будет поставлять значение для массива, у атрибут name поля ввода в качестве значения принимает название массива с квадратными скобками:

Соответственно, сколько полей ввода с одним и тем же именем массива мы укажем, столько значений мы сможем передать на сервер. Так, в данном случае на сервер передается три значения в массиве users:

Отправка массивов на сервер методом POST из формы в PHP

Причем данный принцип применяется и к другим типам полей ввода формы html.

При этом в примерах выше передавался обычный массив, каждый элемент которого в качестве ключа имеет числовой индекс. Соотвенно, используя индекс, мы можем получить определенный элемент массива:

$firstUser = $_POST["users"][0]; echo $firstUser;

Но также мы можем в элементах формы явным образом указать ключи:

     $secondUser
$thirdUser"; > ?>

Форма ввода данных

User 1:

User 2:

User 3:

Например, первое поле добавляет в массив элемент с ключом «first»

Поэтому на сервере мы можем с помощью данного ключа получить соответствующий элемент:

$firstUser = $_POST["users"]["first"];

Источник

$_POST

Ассоциативный массив данных, переданных скрипту через HTTP методом POST при использовании application/x-www-form-urlencoded или multipart/form-data в заголовке Content-Type запроса HTTP.

Примеры

Пример #1 Пример использования $_POST

Подразумевается, что пользователь отправил через POST name=Иван

Результатом выполнения данного примера будет что-то подобное:

Примечания

Замечание:

Это ‘суперглобальная’ или автоматическая глобальная переменная. Это просто означает, что она доступна во всех контекстах скрипта. Нет необходимости выполнять global $variable; для доступа к ней внутри метода или функции.

Смотрите также

User Contributed Notes 6 notes

One feature of PHP’s processing of POST and GET variables is that it automatically decodes indexed form variable names.

I’ve seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

With the first example you’d have to do string parsing / regexes to get the correct values out so they can be married with other data in your app. whereas with the second example.. you will end up with something like:
var_dump ( $_POST [ ‘person’ ]);
//will get you something like:
array (
0 => array( ‘first_name’ => ‘john’ , ‘last_name’ => ‘smith’ ),
1 => array( ‘first_name’ => ‘jane’ , ‘last_name’ => ‘jones’ ),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate «compartment» arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it’s better to define your indexes explicitly.

I know it’s a pretty basic thing but I had issues trying to access the $_POST variable on a form submission from my HTML page. It took me ages to work out and I couldn’t find the help I needed in google. Hence this post.

Make sure your input items have the NAME attribute. The id attribute is not enough! The name attribute on your input controls is what $_POST uses to index the data and therefore show the results.

If you want to receive application/json post data in your script you can not use $_POST. $_POST does only handle form data.
Read from php://input instead. You can use fopen or file_get_contents.

// Get the JSON contents
$json = file_get_contents ( ‘php://input’ );

// decode the json data
$data = json_decode ( $json );
?>

There’s an earlier note here about correctly referencing elements in $_POST which is accurate. $_POST is an associative array indexed by form element NAMES, not IDs. One way to think of it is like this: element «id=» is for CSS, while element «name text» name=»txtForm»>.

Note that $_POST is NOT set for all HTTP POST operations, but only for specific types of POST operations. I have not been able to find documentation, but here’s what I’ve found so far.

In other words, for standard web forms.

A type used for a generic HTTP POST operation.

For a page with multiple forms here is one way of processing the different POST values that you may receive. This code is good for when you have distinct forms on a page. Adding another form only requires an extra entry in the array and switch statements.

if (!empty( $_POST ))
// Array of post values for each different form on your page.
$postNameArr = array( ‘F1_Submit’ , ‘F2_Submit’ , ‘F3_Submit’ );

// Find all of the post identifiers within $_POST
$postIdentifierArr = array();

foreach ( $postNameArr as $postName )
if ( array_key_exists ( $postName , $_POST ))
$postIdentifierArr [] = $postName ;
>
>

// Only one form should be submitted at a time so we should have one
// post identifier. The die statements here are pretty harsh you may consider
// a warning rather than this.
if ( count ( $postIdentifierArr ) != 1 )
count ( $postIdentifierArr ) < 1 or
die( «\$_POST contained more than one post identifier: » .
implode ( » » , $postIdentifierArr ));

// We have not died yet so we must have less than one.
die( «\$_POST did not contain a known post identifier.» );
>

switch ( $postIdentifierArr [ 0 ])
case ‘F1_Submit’ :
echo «Perform actual code for F1_Submit.» ;
break;

case ‘Modify’ :
echo «Perform actual code for F2_Submit.» ;
break;

case ‘Delete’ :
echo «Perform actual code for F3_Submit.» ;
break;
>
>
else // $_POST is empty.
echo «Perform code for page without POST data. » ;
>
?>

Источник

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.

Источник

Оцените статью