- Как передать php массив методом post
- Post Array From HTML Form To PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- HTML POST ARRAY TO PHP
- EXAMPLE 1) POST A SIMPLE ARRAY TO PHP
- 1A) THE HTML
- 1B) SERVER-SIDE PHP
- EXAMPLE 2) POST NESTED ARRAY TO PHP
- 2A) THE HTML
- 2B) SERVER-SIDE PHP
- EXAMPLE 3) POSTING ARRAY WITH AJAX
- 3A) THE HTML
- 3B) THE JAVASCRIPT
- 3C) SERVER PHP
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- ONLY FOR PHP!
- JSON ENCODE-DECODE
- LINKS & REFERENCES
- YOUTUBE TUTORIAL
- INFOGRAPHICS CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- How to submit an associative array with HTML & PHP
- Latest Posts
- Scan Your Docker Images and Containers with VirusTotal: A Step-by-Step Guide
- Bitbucket for Newbies: Mastering Basic Commands and Collaborating on Code
- Accelerate Your Performance Testing on Ubuntu with k6 and Postman-to-k6
- Solve the “Cannot read properties of undefined (reading ‘type’)” error with these simple fixes
- Solving the ‘tail: inotify resources exhausted’ Error on Ubuntu
- Post Array From a Form in PHP
- Use the POST Method to Send an Array From a Form in PHP
- Related Article — PHP Array
Как передать 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 с дополнительными заголовкам, показанными выше
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
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; >
- Collect data from the HTML form.
- Optional, we can manually append more fields to the data.
- 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.
EXTRA BITS & LINKS
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.
LINKS & REFERENCES
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
Search
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.
How to submit an associative array with HTML & PHP
This post will show you how to submit an associative array with HTML and PHP. This concept is quite useful when you need to submit array-type data such as shopping cart information.
Feel free to skip to ‘HTML forms and input‘ or to ‘Submitting Array data through HTML‘ if you’re quite familiar with the syntax of PHP’s array() function.
Latest Posts
Scan Your Docker Images and Containers with VirusTotal: A Step-by-Step Guide
Bitbucket for Newbies: Mastering Basic Commands and Collaborating on Code
Accelerate Your Performance Testing on Ubuntu with k6 and Postman-to-k6
Solve the “Cannot read properties of undefined (reading ‘type’)” error with these simple fixes
December 19, 2022 May 1, 2023
Solving the ‘tail: inotify resources exhausted’ Error on Ubuntu
December 18, 2022 May 1, 2023
Copyright 2018-2022 Anto Online.
All rights reserved. Please consider the information, scripts and instructions carefully before using it yourself. Make sure you have ample backups! The information, scripts and instructions are provided without warranty. Consult a professional if you are unsure. Anto does not speak on behalf of any company and our opinions are our own.
The feature images have been provided by pexels.com and unsplash.com.
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."
"; >
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.