METANIT.COM

How to get POST array value in PHP

This article will introduce the basic usage of PHP’s post array to get a value from an input form. The article will also highlight some important points about how to use post arrays, what they are used for, and where you can find more information about them.

PHP provides an array data type for storing collections of values. The POST variable is a form input that gets sent to your PHP code by the web browser, and it allows you to store multiple values passed in from the HTML form.

Читайте также:  Php ini где лежит ubuntu nginx

An Introduction To POST Arrays in PHP.

A POST array stores data that was sent to the server by a form.

Both these methods place limitations on what can be sent to the server, GET requests are limited to 8-bit ASCII and browsers may prevent more than 2kb of data from being submitted in a single transaction.

POST arrays can store extremely large amounts of data without any limitations. Imagine you have an HTML form that asks people for their entire resume, in this case, it would make sense to save the data submitted by the form to a POST array.

How are POST arrays created?

Creating a new PHP post array is different than creating a normal array because you must tell PHP which special variable name it should use to store the post data.

There are many special variables that PHP uses, but we’re only concerned with $_POST . $_POST contains all values submitted via the HTTP POST method. $_REQUEST – Contains all values submitted via any method (GET, POST, COOKIE, etc).

As mentioned earlier GET requests can’t send very much data at once and as such, they shouldn’t be used for sending large amounts of information (like user uploads) or large forms (like user resumes).

How to get POST array value in PHP

To get all post data in PHP, we have to use the $_POST superglobal variable. You can retrieve the value of a specific key using $_POST[‘key’] syntax but if the key does not exist then this returns an empty string.

If you want to check that a given key exists or not, use the isset() function, for example:

If you want to know whether the given POST array has any content, use empty() function, for example:

Retrieve post array values

If you want to pass an array into a post variable you can do this like below-

 Cooking  
Singing
Playing
Swimming

We now want to see which hobby the user has selected.

Источник

Array post method in php

В прошлых темах была рассмотрена отправка на сервер отдельных значений. Однако отправка набора значений, то есть массивов в 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 Array From a Form in PHP

Post Array From a Form in PHP

This tutorial shows how to use the POST method to send an array from an HTML form in PHP.

Use the POST Method to Send an Array From a Form in PHP

We use the POST method to send data from a form in PHP.

The POST method is an HTTP request method that creates or adds resources to the server. We use it when we have to send sensitive information like passwords.

We need to specify the method attribute as post in the form to send a POST request. The action attribute in the form is where the request is sent. Then, we can use the $_POST superglobal variable to access the data.

We can send the data easily with the POST method in a form. For example, we can use the value of the name attribute in the $_POST array to access the data. The example is shown below.

form action="action.php" method="post">  input type="input" name ="name"> br>  input type="submit" value="Submit">  form> 
$name = $_POST['name']; echo $name"
"
;

But, if we have to send an array of data from the form, we should add the [] sign after the value of the name attribute.

For example, we will need to send an array of data from a form while working with checkboxes. In such conditions, we can use the same value for the name attribute in all checkbox options and add the [] after the value.

For example, we need to create a form where users can select multiple checkboxes. Here, we should ensure that all the checked items are sent to the server.

First, create a form with the action attribute set to action.php . Next, set the method attribute to post , and create a checkbox for Coke using the input tag with the name colddrinks[] .

Similarly, create two other checkboxes for Fanta and Sprite . Use the same colddrinks[] for the name attribute in both checkboxes.

Next, create a PHP file named action.php . Create a $coldDrinks variable and store $_POST[‘colddrinks’] in it.

Make sure not to omit the array symbol after colddrinks . Then, use the foreach loop to display each selected item.

The example below will display the selected name of the cold drinks. In this way, we can use the POST method to send an array from the form in PHP.

form action="action.php" method="post">  input type="checkbox" name ="colddrinks[]" value="Coke"> Coke br>  input type="checkbox" name ="colddrinks[]" value="Fanta"> Fanta br>  input type="checkbox" name ="colddrinks[]" value="Sprite"> Sprite br>  input type="submit" value="Submit">  form> 
$coldDrinks = $_POST['colddrinks']; foreach ($coldDrinks as $coldDrink)  echo $coldDrink."
"
;
>

Источник

Post Array From HTML Form To PHP (Simple Examples)

Welcome to a tutorial on how to post an array from an HTML form to PHP. The “standard” HTML form fields are easy enough. Just add the name attribute to the fields, submit the form, and that’s it. But what if we want to post an array instead?

To post an array from an HTML form to PHP, we simply append a pair of square brackets to the end of the name attribute of the input field. For example:

But how about doing this with AJAX? How about multi-dimensional arrays? How do we handle the post data in PHP? That is what we will walk through in this guide, with examples. Read on to find out!

TLDR – QUICK SLIDES

How To POST An Array From HTML Form To PHP

TABLE OF CONTENTS

HTML POST ARRAY TO PHP

All right, let us now get into the various examples of posting an array to a PHP script.

EXAMPLE 1) POST A SIMPLE ARRAY TO PHP

1A) THE HTML

As in the introduction, we only need to append square brackets [] behind the name to POST arrays to the PHP script.

1B) SERVER-SIDE PHP

Yep, this should be straightforward enough. Since we defined colors[] , $_POST[«colors»] will be an array.

EXAMPLE 2) POST NESTED ARRAY TO PHP

2A) THE HTML

Multi-dimensional array fields are not that difficult either – Just use 2 square brackets, and give the first one a key. That’s it, done.

2B) SERVER-SIDE PHP

No mystery here either – $_POST[«fav»] is a multi-dimensional array as expected.

EXAMPLE 3) POSTING ARRAY WITH AJAX

3A) THE HTML

Not much of a difference here – Still the same HTML form, but using onsubmit=»return save()» to use Javascript AJAX to handle the submission instead.

3B) THE JAVASCRIPT

function save () < // (A) GET FORM DATA var form = document.getElementById("myForm"), data = new FormData(form); // (B) TO MANUALLY APPEND MORE DATA data.append("address[]", "Foo Street 123"); data.append("address[]", "Hello World #234"); // (C) AJAX FETCH fetch("3c-AJAX.php", < method:"POST", body:data >) .then(res => res.text()) .then(res => < console.log(res); // DO SOMETHING >); return false; >
  1. Collect data from the HTML form.
  2. Optional, we can manually append more fields to the data.
  3. Lastly, send the data to the server, and read the server response as text.

3C) SERVER PHP

Nothing to see here… Just a dummy script that will echo whatever is being submitted.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this project, and here is a small section on some extras that may be useful to you.

ONLY FOR PHP!

Before the toxic trolls get angry – Take note that the above method of name=»something[]» works for PHP, but it can be different for other languages. For example, some languages may require all the name attribute to be the same instead:

JSON ENCODE-DECODE

To better support cross-platform data exchange, the common industry practice is to turn the array into a flat string, using JSON encode:

  

On the server side, we can do a JSON decode to get the array back.

P.S. Any programming language can encode-decode a JSON string so long as there is a library or parser.

YOUTUBE TUTORIAL

INFOGRAPHICS CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

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