PHP if GET using if isset
I am new to PHP and I would like to know the correct way to display error in index.php but only if there are errors otherwise it does nothing. The page index.php send the form to login.php if there are errors it return the error to index.php like this:
if ($_GET['error']==2) if ($_GET['error']==3) ?>
How can I fix it the correct way? Some uses the if isset but I dont know how to use this funtion it give me errors
I would be extremely surprised if the code you added slowed the page by more than a few milliseconds.
3 Answers 3
Any time you have repetition like you have presented in your example, try using a function or a storage array . Though your code probably isn’t going much slower, try something like this:
Programming for you, three different ways to solve the same problem. This method is definitely useful when you use a large application and have specific error codes.
@Devon Oh an index notice. Yeah that is true. Man for such a short code, this has been a lot of work!
isset isn’t provided anywhere in your code, but this also presents an opportunity to introduce you to switch.
Instead of using different if’s, you can combine it all into one switch. This is similar to using elseif but neater (in my opinion).
isset in PHP from the documentation is to determine if a variable is set and is not NULL. Refer here
This is how you can use it in your case.
Assuming the URL is something like index.php?error=1
if( isset($_GET['error']) ) < if( $_GET['error'] == 1 ) elseif( $_GET['error'] == 2 ) elseif( $_GET['error'] == 3 ) >
Using elseif can terminate the execution once you reach any error code. For example, if you have error=2 it will not check if the error=3 thus makes the execution faster. But as Scopey mentioned above, the difference of execution time for this kind of thing is actually something that you don’t have to worry.
Hope this helps. Thank you.
isset
Если переменная была удалена с помощью unset() , то она больше не считается установленной. isset() вернет FALSE , если проверяемая переменная имеет значение NULL . Следует помнить, что NULL -байт («\0») не является эквивалентом константе PHP NULL .
Если были переданы несколько параметров, то isset() вернет TRUE только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределенная переменная.
Список параметров
Возвращаемые значения
Возвращает TRUE , если var определена и значение отличное от NULL , и FALSE в противном случае.
Список изменений
Проверка нечислового индекса строки теперь возвращает FALSE .
Примеры
Пример #1 Пример использования isset()
// Проверка вернет TRUE, поэтому текст будет напечатан.
if (isset( $var )) echo «Эта переменная определена, поэтому меня и напечатали.» ;
>
// В следующем примере мы используем var_dump для вывода
// значения, возвращаемого isset().
var_dump (isset( $a )); // TRUE
var_dump (isset( $a , $b )); // TRUE
var_dump (isset( $a )); // FALSE
var_dump (isset( $a , $b )); // FALSE
$foo = NULL ;
var_dump (isset( $foo )); // FALSE
Функция также работает с элементами массивов:
$a = array ( ‘test’ => 1 , ‘hello’ => NULL , ‘pie’ => array( ‘a’ => ‘apple’ ));
var_dump (isset( $a [ ‘test’ ])); // TRUE
var_dump (isset( $a [ ‘foo’ ])); // FALSE
var_dump (isset( $a [ ‘hello’ ])); // FALSE
// Элемент с ключом ‘hello’ равен NULL, поэтому он считается неопределенным
// Если Вы хотите проверить существование ключей со значением NULL, используйте:
var_dump ( array_key_exists ( ‘hello’ , $a )); // TRUE
// Проверка вложенных элементов массива
var_dump (isset( $a [ ‘pie’ ][ ‘a’ ])); // TRUE
var_dump (isset( $a [ ‘pie’ ][ ‘b’ ])); // FALSE
var_dump (isset( $a [ ‘cake’ ][ ‘a’ ][ ‘b’ ])); // FALSE
Пример #2 isset() и строковые индексы
В PHP 5.4 был изменен способ обработки строковых индексов в isset() .
$expected_array_got_string = ‘somestring’ ;
var_dump (isset( $expected_array_got_string [ ‘some_key’ ]));
var_dump (isset( $expected_array_got_string [ 0 ]));
var_dump (isset( $expected_array_got_string [ ‘0’ ]));
var_dump (isset( $expected_array_got_string [ 0.5 ]));
var_dump (isset( $expected_array_got_string [ ‘0.5’ ]));
var_dump (isset( $expected_array_got_string [ ‘0 Mostel’ ]));
?>?php
Результат выполнения данного примера в PHP 5.3:
bool(true) bool(true) bool(true) bool(true) bool(true) bool(true)
Результат выполнения данного примера в PHP 5.4:
bool(false) bool(true) bool(true) bool(true) bool(false) bool(false)
Примечания
isset() работает только с переменными, поэтому передача в качестве параметров любых других значений приведет к ошибке парсинга. Для проверки определения констант используйте функцию defined() .
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Замечание:
При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.
Смотрите также
- empty() — Проверяет, пуста ли переменная
- __isset()
- unset() — Удаляет переменную
- defined() — Проверяет существование указанной именованной константы
- Таблица сравнения типов
- array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
- is_null() — Проверяет, является ли значение переменной равным NULL
- Оператор управления ошибками @
If isset $_POST
I have a form on one page that submits to another page. There, it checks if the input mail is filled. If so then do something and if it is not filled, do something else. I don’t understand why it always says that it is set, even if I send an empty form. What is missing or wrong? step2.php :
All text-like inputs and textareas present in your form will be submitted to the server even if their values are empty strings.
15 Answers 15
Most form inputs are always set, even if not filled up, so you must check for the emptiness too.
Since !empty() is already checks for both, you can use this:
Minor thing. I think it’s preferable to avoid the ! operator in cases like this (easier to read, less chance of error, etc.) and reverse the logic. if (empty())*> else*>
I don’t see why it would be preferrable to avoid !empty() . I will admit, though, that I prefer to write failing conditions before successful conditions.
Caution though, and not fall in the habit of always comparing with empty. This works well in the case of the email, but if you expect the user could input 0 (as integer or string) empty will return TRUE.
Use !empty instead of isset . isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER[‘REQUEST_METHOD’] == ‘POST’
You should mention that use BOTH isset and !empty to prevent error. EDIT: Whoops, it does apparently Learning every day then Ref
I tried and both works fine. Why is $_SERVER[‘REQUEST_METHOD’] == ‘POST’ better? What does it exactly do? can it refers to a specific input or it is generic to the form?
$_SERVER[‘REQUEST_METHOD’] ensures user has submitted form. $_POST can be empty even in this case. Consider this form: , submitting it will send nothing to the action, but request type will be post . Or it can be done with curl: curl -X POST http://example.com/processor.php . If processor contains code like echo $_SERVER[‘REQUEST_METHOD’]. ‘ ‘.var_export(empty($_POST),1); , you will see POST true
isset() can be appropriate when you specify a key within $_POST AND want to allow a falsey value like 0 . Particular to email value submissions, using !empty() is an inadequate tool to validate an email address.
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
empty space is considered as set. You need to use empty() for checking all null options.
If you send the form empty, $_POST[‘mail’] will still be sent, but the value is empty. To check if the field is empty you need to check
if(isset($_POST["mail"]) && trim($_POST["mail"]) != "")
if($_POST['username'] and $_POST['password'])
if(!empty($_POST['username']) and !empty($_POST['password']))
According with the PHP type comparison tables you are absolutely right. A simple boolean does the work of the empty function to check the empty string.
@ICE It can be easily bypassed by prefixing the variables with @ ,i.e: @$_POST[‘username’] . Thank you for noticing that.
Add the following attribute to the input text form: required=»required» . If the form is not filled, it will not allow the user to submit the form.
Relying on client-side validation is not enough. It is trivial to manually circumvent client-side defenses. For improved security, strong validations need to be implemented on the server-side. As stated elsewhere on this page isset() will not work as required by the OP.
I totally agree. Wrote this answer a long back. This answer suggests the frontend side of things. Ideally validation should be done both in the frontend and the backend with error passing from server side and handling the error on the frontend.
Bottomline to researchers: this answer’s server-side check does not ensure that the form field is filled in.
Maybe you can try this one:
if (isset($_POST['mail']) && ($_POST['mail'] !=0)) < echo "Yes, mail is set"; >else
This is more simply written as !empty() . It also makes your snippet less intuitive by checking for not zero on an email field’s value.
Lets Think this is your HTML Form in step2.php
I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your
if(isset($_POST['mail']) && !empty($_POST['mail']))
Where $db is your Database Connection.
isset() followed by !empty() is an antipattern that should not exist in any code for any reason. It is doing too much work. If !empty() is the desired logic, then also checking isset() is pointless. Also, do not use mysqli_real_escape_string anymore; use prepared statements.
Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers.
form name="new user" method="post" action="step2_check.php">
See how you are unconditionally declaring $Email before checking if it is not empty? This is doing unnecessary work. !empty() does two things. It checks if a variable is declared and checks if it is truthy. Since the variable is certainly declared, you can just use if ($Email) < with the exact same effect.
To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well.
$errMess="Didn't test"; // This message should not show if(isset($_POST["foo"])) < // does it exist or not $foo = $_POST["foo"]; // save $foo from POST made by HTTP request if(empty($foo))< // exist but it's null $errMess="Empty"; // #1 Nothing in $foo it's emtpy >else < // exist and has data $errMess="None"; // #2 Something in $foo use it now >> else < // couldn't find ?foo=dataHere $errMess="Missing"; // #3 There's no foo in request data >echo "Was there a problem: ".$errMess."!";
if (isset($_POST["mail"]) !== false) < echo "Yes, mail is set"; >else
This advice was given years earlier stackoverflow.com/a/13045314/2943403 and adds no new value to the page.
$-POST METHOD: if we use POST method in the form tag to pass data,we can find data in the server using $_POST array.using this array name we fetch data from server.($_POST[‘name’])Information sent from a form with the POST method is invisible to others(all names/values are embedded within the body of the HTTP request) and has no limits n the amount of information to send. Example Code:
form submitted";echo"your name is". $_POST['name']."
"; echo "your roll number is". $_POST['roll']."
";>> else Name:
Roll:
?>
Not only does this answer ignore the OP’s scenario, this answer does nothing to check if a field is «filled».
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.