Php post array to php

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?

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

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.

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

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.

The first comment answers this.

The name tag can work as an array.

You could put it in the session:

Or if you want to send it via a form you can serialize it:

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.

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?:

This would be written into your form like so:

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.

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.

Источник

$_POST

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_POST — Переменные HTTP POST

Описание

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

Примеры

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

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

Примечания

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

User Contributed Notes 7 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:

Example pseudo code:

Many web sites do this:

When they could do this:

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.

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

$_POST _is_ set for:

In other words, for standard web forms.

$_POST is NOT set for:

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.

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

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

Источник

Retrieve post array values

Is this the correct approach?

6 Answers 6

Your code would then be:

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

php automatically detects $_POST and $_GET-arrays so you can juse:

and $qty will by a php-Array. Now you can access it by:

if you are not sure about the format of the received data structure you can use:

to see how it is stored.

My version of PHP 4.4.4 throws an error: Fatal error: Call to undefined function: size()

I changed size to count and then the routine ran correctly.

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

try using filter_input() with filters FILTER_SANITIZE_SPECIAL_CHARS and FILTER_REQUIRE_ARRAY as shown

then you can iterate through it nicely as

PHP handles nested arrays nicely

I prefer foreach insted of for, because you do not need to heandle the size.

Not the answer you’re looking for? Browse other questions tagged php jquery arrays or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Php post array to php

Когда происходит отправка данных формы PHP-скрипту, информация из этой формы автоматически становится доступной ему. Существует несколько способов получения этой информации, например:

Пример #1 Простая HTML-форма

Есть только два способа получить доступ к данным из форм HTML. Доступные сейчас способы приведены ниже:

Пример #2 Доступ к данным из простой HTML-формы, отправленной через POST

PHP также понимает массивы в контексте переменных формы (смотрите соответствующие ЧАВО). К примеру, вы можете сгруппировать связанные переменные вместе или использовать эту возможность для получения значений списка множественного выбора select. Например, давайте отправим форму самой себе, а после отправки отобразим данные:

Пример #3 Более сложные переменные формы

Имена переменных кнопки-изображения

При отправке формы вместо стандартной кнопки можно использовать изображение с помощью тега такого вида:

HTTP Cookies

Замечание: Начиная с PHP 7.2.34, 7.3.23 и 7.4.11, соответственно, имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.

Если вы хотите присвоить множество значений одной переменной cookie, вы можете присвоить их как массив. Например:

Обратите внимание, что cookie заменит предыдущую cookie с тем же именем в вашем браузере, если только путь или домен не отличаются. Так, для приложения корзины покупок вы, возможно, захотите сохранить счётчик. То есть:

Пример #4 Пример использования setcookie()

Точки в именах приходящих переменных

Как правило, PHP не меняет передаваемых скрипту имён переменных. Однако следует отметить, что точка не является корректным символом в имени переменной PHP. Поэтому рассмотрим такую запись:

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

Определение типов переменных

Список изменений

ВерсияОписание
7.2.34, 7.3.23, 7.4.11имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.

User Contributed Notes 30 notes

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.

Important: Pay attention to the following security concerns when handling user submitted data :

This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

Normally the ‘value’ attribute of the HTML ‘input’ tag (in this case «Delete») that creates the submit button can be accessed in PHP after post like this:

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you’re dealing with user management in some administrative interface. You are presented with a list of user names queried from a database and wish to add a «Delete» and «Modify» button next to each of the names in the list. Naturally the ‘value’ of our buttons in the HTML form that we want to display will be «Delete» and «Modify» since that’s what we want to appear on the buttons’ faceplates.

Using arrays is the way to go. Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON’T wish to protect that number from the public, we can make the ‘action_button’ into an array and use the user’s unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the ‘value’ of the button («Delete» or «Modify») and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either «Modify» or «Delete», as well as the unique number of the user:

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Источник

Convert PostgreSQL array to PHP array

I have trouble reading Postgresql arrays in PHP. I have tried explode(), but this breaks arrays containing commas in strings, and str_getcsv() but it’s also no good as PostgreSQL doesn’t quote the Japanese strings.

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

10 Answers 10

If you have PostgreSQL 9.2 you can do something like this:

The result will return the array as JSON

Then on the php side issue:

You can also convert back. Here are the JSON functions page

As neither of these solutions work with multidimentional arrays, so I offer here my recursive solution that works with arrays of any complexity:

I haven’t tested it too much, but looks like it works. Here you have my tests with results:

P.S.: I know this is a very old post, but I couldn’t find any solution for postgresql pre 9.2

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

Reliable function to parse PostgreSQL (one-dimensional) array literal into PHP array, using regular expressions:

There are only quotes around the array parts if they contain special characters like whitespace or punctuation.

So if there are quotes, I make the string a valid json string and then use the build-in parse json function. Otherwise I use explode.

If you have control of the query that’s hitting the database, why don’t you just use unnest() to get the results as rows instead of Postgres-arrays? From there, you can natively get a PHP-array.

This sidesteps the overhead and maintenance-issues you’d incur by trying to convert the array’s string-representation yourself.

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

If you can foresee what kind text data you can expect in this field, you can use array_to_string function. It’s available in 9.1

Now I can split this string using PHP function explode :

You can use any sequence of characters to separate elements of array.

Php post array to php. Смотреть фото Php post array to php. Смотреть картинку Php post array to php. Картинка про Php post array to php. Фото Php post array to php

Postgresql arrays look like this:

You can just simply replace first < and last >with [ and ] respectively and then json_decode that.

But his solution works only for one-dimensional arrays.

Here the solution either for one-dimensional and multidimensional arrays:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *