Php check post var

$_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

Examples

Example #1 $_POST example

Assuming the user POSTed name=Hannes

The above example will output something similar to:

Notes

Note:

This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

See Also

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. » ;
>
?>

Источник

Php check post var

Когда происходит отправка данных формы PHP-скрипту, информация из этой формы автоматически становится доступной ему. Существует несколько способов получения этой информации, например:

Пример #1 Простая HTML-форма

Есть только два способа получить доступ к данным из форм HTML. Доступные сейчас способы приведены ниже:

Пример #2 Доступ к данным из простой HTML-формы, отправленной через POST

GET-форма используется аналогично, за исключением того, что вместо POST, вам нужно будет использовать соответствующую предопределённую переменную GET. GET относится также к QUERY_STRING (информация в URL после ‘?’). Так, например, http://www.example.com/test.php?id=3 содержит GET-данные, доступные как $_GET[‘id’] . Смотрите также $_REQUEST .

Замечание:

Точки и пробелы в именах переменных преобразуется в знаки подчёркивания. Например, станет $_REQUEST[«a_b»] .

PHP также понимает массивы в контексте переменных формы (смотрите соответствующие ЧАВО). К примеру, вы можете сгруппировать связанные переменные вместе или использовать эту возможность для получения значений списка множественного выбора select. Например, давайте отправим форму самой себе, а после отправки отобразим данные:

Пример #3 Более сложные переменные формы

if ( $_POST ) echo ‘

' ; 
echo htmlspecialchars ( print_r ( $_POST , true ));
echo '

‘ ;
>
?>

Имя:

Email:

Пиво:

Замечание: Если внешнее имя переменной начинается с корректного синтаксиса массива, завершающие символы молча игнорируются. Например, станет $_REQUEST[‘foo’][‘bar’] .

Имена переменных кнопки-изображения

При отправке формы вместо стандартной кнопки можно использовать изображение с помощью тега такого вида:

Когда пользователь щёлкнет где-нибудь на изображении, соответствующая форма будет передана на сервер с двумя дополнительными переменными — sub_x и sub_y . Они содержат координаты нажатия пользователя на изображение. Опытные программисты могут заметить, что на самом деле имена переменных, отправленных браузером, содержат точку, а не подчёркивание, но PHP автоматически преобразует точку в подчёркивание.

HTTP Cookies

PHP прозрачно поддерживает HTTP cookies как определено в » RFC 6265. Cookies — это механизм для хранения данных в удалённом браузере и, таким образом, отслеживания и идентификации вернувшихся пользователей. Вы можете установить cookies, используя функцию setcookie() . Cookies являются частью HTTP-заголовка, поэтому функция SetCookie должна вызываться до того, как браузеру будет отправлен какой бы то ни было вывод. Это то же ограничение, что и для функции header() . Данные, хранящиеся в cookie, доступны в соответствующих массивах данных cookie, таких как $_COOKIE и $_REQUEST . Подробности и примеры смотрите в справочной странице setcookie() .

Замечание: Начиная с PHP 7.2.34, 7.3.23 и 7.4.11, соответственно, имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.

Если вы хотите присвоить множество значений одной переменной cookie, вы можете присвоить их как массив. Например:

setcookie ( «MyCookie[foo]» , ‘Testing 1’ , time ()+ 3600 );
setcookie ( «MyCookie[bar]» , ‘Testing 2’ , time ()+ 3600 );
?>

Это создаст две разные cookie, хотя в вашем скрипте MyCookie будет теперь одним массивом. Если вы хотите установить именно одну cookie со множеством значений, сначала рассмотрите возможность использования к значениям такие функции, как serialize() или explode() .

Обратите внимание, что cookie заменит предыдущую cookie с тем же именем в вашем браузере, если только путь или домен не отличаются. Так, для приложения корзины покупок вы, возможно, захотите сохранить счётчик. То есть:

Пример #4 Пример использования setcookie()

if (isset( $_COOKIE [ ‘count’ ])) $count = $_COOKIE [ ‘count’ ] + 1 ;
> else $count = 1 ;
>
setcookie ( ‘count’ , $count , time ()+ 3600 );
setcookie ( «Cart[ $count ]» , $item , time ()+ 3600 );
?>

Точки в именах приходящих переменных

Как правило, PHP не меняет передаваемых скрипту имён переменных. Однако следует отметить, что точка не является корректным символом в имени переменной PHP. Поэтому рассмотрим такую запись:

В данном случае интерпретатор видит переменную $varname , после которой идёт оператор конкатенации, а затем голая строка (то есть, не заключённая в кавычки строка, не соответствующая ни одному из ключевых или зарезервированных слов) ‘ext’. Очевидно, что это не даст ожидаемого результата.

По этой причине важно отметить, что PHP будет автоматически заменять любые точки в именах, приходящих переменных на символы подчёркивания.

Определение типов переменных

Поскольку PHP определяет типы переменных и преобразует их (как правило) по мере необходимости, не всегда очевидно, какой тип имеет данная переменная в любой момент времени. PHP содержит несколько функций, позволяющих определить тип переменной, таких как: gettype() , is_array() , is_float() , is_int() , is_object() и is_string() . Смотрите также раздел Типы.

HTTP является текстовым протоколом, и большинство, если не всё, содержимое, которое приходит в суперглобальные массивы, например, $_POST и $_GET , останется в виде строк. PHP не будет преобразовывать значения в определённый тип. В приведённом ниже примере $_GET[«var1»] будет содержать строку «null», а $_GET[«var2»] — строку «123».

Список изменений

Версия Описание
7.2.34, 7.3.23, 7.4.11 имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.

User Contributed Notes 30 notes

The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) — chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.

Important: Pay attention to the following security concerns when handling user submitted data :

This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

Normally the ‘value’ attribute of the HTML ‘input’ tag (in this case «Delete») that creates the submit button can be accessed in PHP after post like this:

$_POST [ ‘action_button’ ];
?>

We of course use the ‘name’ of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you’re dealing with user management in some administrative interface. You are presented with a list of user names queried from a database and wish to add a «Delete» and «Modify» button next to each of the names in the list. Naturally the ‘value’ of our buttons in the HTML form that we want to display will be «Delete» and «Modify» since that’s what we want to appear on the buttons’ faceplates.

Both buttons (Modify and Delete) will be named «action_button» since that’s what we want to index the $_POST array with. In other words, the ‘name’ of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go. Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON’T wish to protect that number from the public, we can make the ‘action_button’ into an array and use the user’s unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the ‘value’ of the button («Delete» or «Modify») and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either «Modify» or «Delete», as well as the unique number of the user:

$submitted_array = array_keys ( $_POST [ ‘action_button’ ]);
echo ( $_POST [ ‘action_button’ ][ $submitted_array [ 0 ]] . » » . $submitted_array [ 0 ]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST[‘action_button’], like we did above, we will extract the string that was used as ‘value’ in the HTML code ‘input’ tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Источник

Читайте также:  Working with csv files python
Оцените статью