Check if $_POST exists
301517 просмотра
13 ответа
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
Автор: eliwedel Источник Размещён: 12.11.2019 09:02Ответы (13)
154 плюса
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Автор: ehmad
Размещён: 16.08.2010 08:29
54 плюса
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Автор: Dheeraj Bhaskar
Размещён: 06.10.2014 06:33
32 плюса
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL;
and $_POST['x'] = '';
isset($_POST['x'])
will return false
on the first example, but will return true
on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST
is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
Автор: Rafael Размещён: 16.08.2010 09:1528 плюса
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Автор: John Magnolia
Размещён: 18.02.2015 08:45
19 плюса
12 плюса
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null
it means that key exists and was send but value was null
The other option is isset()
which which will check if array key exists and if it was set
The last option is to use empty()
which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset()
and empty()
can be good as well.
9 плюса
- In that case using method
isset
is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists
is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
- Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
6 плюса
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Автор: linuxatico
Размещён: 05.12.2013 08:43
4 плюса
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
Автор: Augustus Francis
Размещён: 02.09.2013 05:53
3 плюса
3 плюса
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
Автор: jezmck
Размещён: 16.08.2010 08:25
2 плюса
if( isset($_POST['fromPerson']) )
is right.
You can use a function and return, better then directing echo.
Автор: Cristian Weiser Размещён: 14.07.2014 01:071 плюс
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
Автор: Raymondim
Размещён: 03.07.2016 06:15
Вопросы из категории :
- php Как вы отлаживаете PHP-скрипты?
- php Заставьте XAMPP / Apache обслуживать файл вне htdocs
- php Как включить файлы PHP, которые требуют абсолютного пути?
- php Скрипт входа со скрытыми кнопками
- php How can I find unused functions in a PHP project
- php Эффективное изменение размера JPEG изображения в PHP
- php MySQL или PDO - каковы плюсы и минусы?
- php Как бы вы внедрили аутентификацию на основе FORM без резервной базы данных?
- php Самый простой способ профилировать скрипт PHP
- php Изображения в PHP
- php PHP эквивалент .NET / Java toString ()
- php В чем разница между | и || или операторы?
- php Пул соединений в PHP
- php PHP выполнить фоновый процесс
- php htmlentities () против htmlspecialchars ()
- php Генерирование (псевдо) случайных буквенно-цифровых строк
- php Какой лучший способ получить дробную часть числа с плавающей точкой в ??PHP?
- php Как реализовать кеш HTML для сайта PHP?
- php Как я могу предотвратить SQL-инъекцию в PHP?
- php PHP: Как расширить / сжать Tinyurls