METANIT.COM

Access post array 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"];

Источник

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.

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.

Источник

How to use $_GET and $_POST arrays in PHP

GET and POST are two essential methods when a web communicates with the server. These methods determine whether the web is posting data to or getting data from the server.

PHP which is a language that was created for making the web, give us a useful way to handle the data in process of Post or Get method. In this post, we’re getting to know about $_GET and $_POST array in PHP.

There’s one thing you need to know that in a .php file, we can write HTML and PHP together, the PHP code must be written in between the tag ;

How to pass variables in URL

First of all, we need to know how to pass some variables or parameters in the URL.

http://localhost/task1.php/?firstName=Sam&lastName=Nguyen
  1. To declare the variable, we use “?” mark
  2. then the variable name
  3. “=” sign to assign a value
  4. the last thing is the value itself
  5. If you have multiple variables, separating them by “&” mark.

Using $_GET array in PHP

Now that we know how to pass the variables in the URL, we’re going to get it in PHP using $_GET. $_GET is a built-in variable of PHP which is an array that holds the variable that we get from the URL.

Since we passed some variable in the URL, we should know what is the name of variables to get it using the syntax $_GET[variable_name] ;

echo $_GET['firstName'] //Sam echo $_GET['firstName'] //Nguyen use "echo" to print the value to web page.

Validate variable in URL

There are two things we will consider here: first if the variable is declared, second if the variable is blank.

Using isset() to check if the variable is declared in URL, this is a function that returns boolean true if the parameter is detected in URL false if not. As long as the variable name is in the URL it will return true.

http://localhost/task1.php/?firstName=Sam&lastName= isset($_GET['firstName']) // true isset($_GET['middleName']) // false isset($_GET['lastName']) // true

As you can see in the code above, the lastName variable hasn’t been provided a valued but it still returns return true since isset() function detect the variable name in URL.

Now we need to check if the variable is empty/blank or not. This is as simple as any other language by comparing the variable to an empty string

http://localhost/task1.php/?firstName=Sam&lastName= $_GET['firstName'] == "" // false $_GET['lastName'] == "" // true

Using $_POST array in PHP

To use the Post method, we definitely need a form in our HTML file to handle data we want to post. The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.

Consider the simple application below, we will demand the user to put in 2 number to add them together.

The form in the code above has 2 data that we want to process that are stored in 2 input fields. Notice that these input fields have different name value. And the value of the name attribute is what we use to access the value of the input fields itself in PHP.

Whenever the post method is triggered by clicking the submit button, PHP will get the value of the variable that we desire to catch.

$_POST["num1"] // this will hold the value of input field with name="num1" $_POST['num2'] // this will hold the value of input field with name="num2"

And then, we will echo/ print out the sum onto the web page

echo $_POST["num1"] + $_POST['num2']

Source code for $_POST:

ADD 2 NUMBER

Источник

Как передать array через POST?

Важно для меня, чтобы я отправил POST запрос и он уже выполнялся сам, чтобы файл start.php не ждал пока в файле script.php завершит свои действия которые могут выполняться в течении 20-30 секунд).
Как я могу это сделать?

Простой 8 комментариев

Чтобы передать массив его нужно сериализовать. Например в JSON — json_encode($ваш_массив); и передавать соответственно уже эти данные. Можно просто в теле запроса, можно каким-нибудь параметром.

Важно для меня, чтобы я отправил POST запрос и он уже выполнялся сам, чтобы файл start.php не ждал пока в файле script.php завершит свои действия

PHP при любом раскладе будет ждать ответ. Чтобы не блокировать страницу нужно использовать AJAX-запросы из под JS.

slo_nik

xEpozZ

Дмитрий Дерепко, так асинхронный код на PHP так же будет ждать выполнения всех запущенных в асинхронности скриптов. Или вы о чем? А на счет форка хз. Честно говоря сам не сталкивался, но слышал, что на длинных запросах, а автор как раз про 20-30 секунд пишет, частенько падает все с ошибками. Хотя может ошибаюсь конечно 🙁

curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

Вот так отправил POST запрос, а как его принять?)
Хотел записать в файл:

file_put_contents(__DIR__ . '/logs/tester.txt', $_POST . PHP_EOL, FILE_APPEND);

— в результате получаю запись: Array

пытался json_decode(_POST) результат не лучше.

Us59, вы отправляете JSON в теле запроса. Чтобы его принять в данном случае нужно считывать его с потока php://

file_put_contents(__DIR__ . '/logs/tester.txt', file_get_contents('php://input') . PHP_EOL, FILE_APPEND);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['json' => json_encode($data)]));
file_put_contents(__DIR__ . '/logs/tester.txt', $_POST['json'] . PHP_EOL, FILE_APPEND);
// Input $data = extract($_POST); // Output $url = 'http://api.example.com'; $data = array('foo' => 'bar'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $result = curl_exec($ch); curl_close($ch);

Можно использовать параметры CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUT, чтобы автоматически разрывать соединение. При отправке запроса будет ошибка, но запрос выполнится:

curl_setopt($ch, CURLOPT_TIMEOUT, 1);

По хорошему, нужно использовать очередь сообщений. Так же можно попробовать запустить процесс в фоновом режиме:
Как правильно запустить внешний скрипт в фоновом режиме?

Еще, как вариант, Вы можете сбросить соединение на стороне script.php без остановки скрипта, если на сервере используется FastCGI (FPM):

Digiport

function wbAuthPostContents($url, $post=null, $username=null,$password=null) < if (func_num_args()==3) < $password=$username; $username=$get; $post=array(); >if (!is_array($post)) $post=(array)$post; $cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password") ); $post=http_build_query($post); $opts = array( 'http'=>array( 'method'=>'POST', 'header'=>$cred, 'content'=>$post ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); return $result; >

Источник

Читайте также:  Название документа
Оцените статью