$_POST
Ассоциативный массив данных, переданных скрипту через HTTP методом POST при использовании application/x-www-form-urlencoded или multipart/form-data в заголовке Content-Type запроса HTTP.
Примеры
Пример #1 Пример использования $_POST
Подразумевается, что пользователь отправил через POST name=Иван
Результатом выполнения данного примера будет что-то подобное:
Примечания
Замечание:
Это ‘суперглобальная’ или автоматическая глобальная переменная. Это просто означает, что она доступна во всех контекстах скрипта. Нет необходимости выполнять global $variable; для доступа к ней внутри метода или функции.
Смотрите также
User Contributed Notes 6 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:
With the first example you’d have to do string parsing / regexes to get the correct values out so they can be married with other data in your app. whereas with the second example.. you will end up with something like:
var_dump ( $_POST [ ‘person’ ]);
//will get you something like:
array (
0 => array( ‘first_name’ => ‘john’ , ‘last_name’ => ‘smith’ ),
1 => array( ‘first_name’ => ‘jane’ , ‘last_name’ => ‘jones’ ),
)
?>
This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate «compartment» arrays or when you want to link your POSTed data into different record handlers in various Frameworks.
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.
I know it’s a pretty basic thing but I had issues trying to access the $_POST variable on a form submission from my HTML page. It took me ages to work out and I couldn’t find the help I needed in google. Hence this post.
Make sure your input items have the NAME attribute. The id attribute is not enough! The name attribute on your input controls is what $_POST uses to index the data and therefore show the results.
If you want to receive application/json post data in your script you can not use $_POST. $_POST does only handle form data.
Read from php://input instead. You can use fopen or file_get_contents.
// Get the JSON contents
$json = file_get_contents ( ‘php://input’ );
// decode the json data
$data = json_decode ( $json );
?>
There’s an earlier note here about correctly referencing elements in $_POST which is accurate. $_POST is an associative array indexed by form element NAMES, not IDs. One way to think of it is like this: element «id=» is for CSS, while element «name text» name=»txtForm»>.
Note that $_POST is NOT set for all HTTP POST operations, but only for specific types of POST operations. I have not been able to find documentation, but here’s what I’ve found so far.
In other words, for standard web forms.
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.
if (!empty( $_POST ))
// Array of post values for each different form on your page.
$postNameArr = array( ‘F1_Submit’ , ‘F2_Submit’ , ‘F3_Submit’ );
// Find all of the post identifiers within $_POST
$postIdentifierArr = array();
foreach ( $postNameArr as $postName )
if ( array_key_exists ( $postName , $_POST ))
$postIdentifierArr [] = $postName ;
>
>
// Only one form should be submitted at a time so we should have one
// post identifier. The die statements here are pretty harsh you may consider
// a warning rather than this.
if ( count ( $postIdentifierArr ) != 1 )
count ( $postIdentifierArr ) < 1 or
die( «\$_POST contained more than one post identifier: » .
implode ( » » , $postIdentifierArr ));
// We have not died yet so we must have less than one.
die( «\$_POST did not contain a known post identifier.» );
>
switch ( $postIdentifierArr [ 0 ])
case ‘F1_Submit’ :
echo «Perform actual code for F1_Submit.» ;
break;
case ‘Modify’ :
echo «Perform actual code for F2_Submit.» ;
break;
case ‘Delete’ :
echo «Perform actual code for F3_Submit.» ;
break;
>
>
else // $_POST is empty.
echo «Perform code for page without POST data. » ;
>
?>
GET, POST, and HEAD requests with PHP’s build-in functions
How to send HTTP requests using the build-in file functions of PHP.
There are a few ways to perform HTTP requests in PHP, in this tutorial we will show how to send a POST and GET request by using the file- functions in combination with stream_context_create.
While using a library like cURL is probably one of the most popular ways to perform HTTP requests, you can also use functions such as file_get_contents and fopen.
While the name of these functions do not exactly indicate that they can also be used for HTTP requests, they do actually work quite well for this, and they are also fairly easy to use.
The stream_context_create function mentioned before is used to gain finer control over various options related to a request.
There should be no disadvantage to using the build-in functions instead of cURL, and unlike what is often claimed, they can be used for both POST and GET requests. However, some hosting companies might disable allow_url_fopen, which will break scripts relying on these methods.
GET Requests
To perform a simple get request, we will first create a $handle variable. We can use this to reference the request when storing the downloaded data in the $contents variable using stream_get_contents.
$handle = fopen("https://beamtic.com/", "rb"); $contents = stream_get_contents($handle); fclose($handle);
The stream_get_contents function automatically downloads a file or web page, however, if you wish to do it manually, for finer control over the process, you may use a while loop in combination with fread:
$handle = fopen("https://beamtic.com/", "rb"); $contents = ''; while (!feof($handle)) $contents .= fread($handle, 8192); > fclose($handle); echo $contents;
In this case the last argument in the fread function is equal to the chunk size, this is usually not larger than 8192 (8*1024). Keep in mind that this can be larger or smaller, but may also be limited by the system PHP is running on. You can optimize your PHP scripts by not using a larger chunk-size than that of your storage device.
One of the simplest ways to download a file, is to use file_get_contents. It requires far less code than using the other methods, but it also offers less control over the process.
$homepage = file_get_contents('https://beamtic.com/'); echo $homepage;
POST Requests
Sending a POST request is not much harder than sending GET. We just have to use the stream_context_create function to add the necessary headers to perform the request.
Again, we can do this both with file_get_contents and fopen; but let us just use file_get_contents for now:
$sURL = "https://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents;
The $sURL variable contains the POST URL.
The $sPD variable contains the data you want to post. Formatting should match the content-type header.
The $aHTTP array has all of the options, including headers, which will be passed on to stream_context_create.
You can also perform POST requests with the fread function.
$sURL = "http://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $handle = fopen($sURL, 'r', false, $context); $contents = ''; while (!feof($handle)) $contents .= fread($handle, 8192); > fclose($handle); echo $contents;
Request Headers
If you got multiple headers, remember to separate them with \r\n
The content-type header tells the server how the posted data is formatted. The application/x-www-form-urlencoded content-type is often used by web applications, but you can also encounter multipart/form-data. If an application does not support the content-type you specify, the POST will usually just fail.
The content header contains the actual data that you want to post. This should be formatted in accordance with the content-type you are using.
Alternatively, you may also add options and headers as shown below, this time adding a referer header:
$aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n";
Additional request headers will be added in the same way; do this by adding a single Carriage return (\r), and a line feed (\n) at the end of each header, followed by whatever header you want to add. Once you have added all the headers, you should end up with something like the below (full script):
$sURL = "https://beamtic.com/api/request-headers"; // The POST URL $aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n"; $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents;
Tools:
You can use the following API endpoints for testing purposes:
https://beamtic.com/api/user-agent
https://beamtic.com/api/request-headers