Php post read array

# Reading Request Data

Usually data sent in a POST request is structured key/value pairs with a MIME type of application/x-www-form-urlencoded . However many applications such as web services require raw data, often in XML or JSON format, to be sent instead. This data can be read using one of two methods.

php://input is a stream that provides access to the raw request body.

$rawdata = file_get_contents("php://input"); // Let's say we got JSON $decoded = json_decode($rawdata); 

$HTTP_RAW_POST_DATA is a global variable that contains the raw POST data. It is only available if the always_populate_raw_post_data directive in php.ini is enabled.

$rawdata = $HTTP_RAW_POST_DATA; // Or maybe we get XML $decoded = simplexml_load_string($rawdata); 

This variable has been deprecated since PHP version 5.6, and was removed in PHP 7.0.

Note that neither of these methods are available when the content type is set to multipart/form-data , which is used for file uploads.

Читайте также:  Css общий синтаксис таблиц стилей

# Reading POST data

Data from a POST request is stored in the superglobal

(opens new window) $_POST in the form of an associative array.

Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.

$from = isset($_POST["name"]) ? $_POST["name"] : "NO NAME"; $message = isset($_POST["message"]) ? $_POST["message"] : "NO MESSAGE"; echo "Message from $from: $message"; 
$from = $_POST["name"] ?? "NO NAME"; $message = $_POST["message"] ?? "NO MESSAGE"; echo "Message from $from: $message"; 

# Reading GET data

Data from a GET request is stored in the superglobal

(opens new window) $_GET in the form of an associative array.

Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.

Example: (for URL /topics.php?author=alice&topic=php )

$author = isset($_GET["author"]) ? $_GET["author"] : "NO AUTHOR"; $topic = isset($_GET["topic"]) ? $_GET["topic"] : "NO TOPIC"; echo "Showing posts from $author about $topic"; 
$author = $_GET["author"] ?? "NO AUTHOR"; $topic = $_GET["topic"] ?? "NO TOPIC"; echo "Showing posts from $author about $topic"; 

# Handling file upload errors

The $_FILES[«FILE_NAME»][‘error’] (where «FILE_NAME» is the value of the name attribute of the file input, present in your form) might contain one of the following values:

  1. UPLOAD_ERR_OK — There is no error, the file uploaded with success.
  2. UPLOAD_ERR_INI_SIZE — The uploaded file exceeds the upload_max_filesize directive in php.ini .
  3. UPLOAD_ERR_PARTIAL — The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  4. UPLOAD_ERR_NO_FILE — No file was uploaded.
  5. UPLOAD_ERR_NO_TMP_DIR — Missing a temporary folder. (From PHP 5.0.3).
  6. UPLOAD_ERR_CANT_WRITE — Failed to write file to disk. (From PHP 5.1.0).
  7. UPLOAD_ERR_EXTENSION — A PHP extension stopped the file upload. (From PHP 5.2.0).

An basic way to check for the errors, is as follows:

 $fileError = $_FILES["FILE_NAME"]["error"]; // where FILE_NAME is the name attribute of the file input in your form switch($fileError)  case UPLOAD_ERR_INI_SIZE: // Exceeds max size in php.ini break; case UPLOAD_ERR_PARTIAL: // Exceeds max size in html form break; case UPLOAD_ERR_NO_FILE: // No file was uploaded break; case UPLOAD_ERR_NO_TMP_DIR: // No /tmp dir to write to break; case UPLOAD_ERR_CANT_WRITE: // Error writing to disk break; default: // No error was faced! Phew! break; > 

# Uploading files with HTTP PUT

(opens new window) for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:

PUT /path/filename.html HTTP/1.1 

Into your PHP code you would then do something like this:

 /* PUT data comes in on the stdin stream */ $putdata = fopen("php://input", "r"); /* Open a file for writing */ $fp = fopen("putfile.ext", "w"); /* Read the data 1 KB at a time and write to the file */ while ($data = fread($putdata, 1024)) fwrite($fp, $data); /* Close the streams */ fclose($fp); fclose($putdata); ?> 

(opens new window) you can read interesting SO question/answers about receiving file via HTTP PUT.

# Passing arrays by POST

Usually, an HTML form element submitted to PHP results in a single value. For example:

pre>  print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo" value="bar"/> button type="submit">Submitbutton> form> 

This results in the following output:

However, there may be cases where you want to pass an array of values. This can be done by adding a PHP-like suffix to the name of the HTML elements:

pre>  print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo[]" value="bar"/> input type="hidden" name="foo[]" value="baz"/> button type="submit">Submitbutton> form> 

This results in the following output:

Array ( [foo] => Array ( [0] => bar [1] => baz ) ) 

You can also specify the array indices, as either numbers or strings:

pre>  print_r($_POST);?> pre> form method="post"> input type="hidden" name="foo[42]" value="bar"/> input type="hidden" name="foo[foo]" value="baz"/> button type="submit">Submitbutton> form> 

Which returns this output:

Array ( [foo] => Array ( [42] => bar [foo] => baz ) ) 

This technique can be used to avoid post-processing loops over the $_POST array, making your code leaner and more concise.

# Remarks

# Choosing between GET and POST

GET requests, are best for providing data that’s needed to render the page and may be used multiple times (search queries, data filters. ). They are a part of the URL, meaning that they can be bookmarked and are often reused.

POST requests on the other hand, are meant for submitting data to the server just once (contact forms, login forms. ). Unlike GET, which only accepts ASCII, POST requests also allow binary data, including file uploads

You can find a more detailed explanation of their differences here

# Request Data Vulnerabilities

Retrieving data from the $_GET and $_POST superglobals without any validation is considered bad practice, and opens up methods for users to potentially access or compromise data through code

(opens new window) . Invalid data should be checked for and rejected as to prevent such attacks.

Request data should be escaped depending on how it is being used in code, as noted here

(opens new window) . A few different escape functions for common data use cases can be found in this answer

Источник

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.

Источник

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