isset() function always returns true [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been figuring out how to do this but it seems not to be working.
My code for the form:
<form name="register" method="POST" action="php\reg.php">
<label>Email:</label>
<input type="email" name="email"/>
.
.
.
</form>
Code for the "reg.php" file:
if (isset($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>
Problem is, whenever I input or not in the email textbox, isset function always returns the true value. how can I resolve this??

All answers that tell you about using isset() and empty() to check form values are... bad. Use one of the filter functions to check if a POST/GET/COOKIE variable is present and validate or sanitize it. Here is an example:
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === NULL) {
die("Email field not present in form");
} elseif ($email === FALSE) {
die("Email is present but its value is invalid");
}
Note: the empty() function has a gotcha and I would not recommend using it for form validation unless you understand exactly what it does: it returns true for all falsy values. This means 0 is considered empty which is often an acceptable value in certain cases. Example (bad one):
if (empty($_POST["number_of_children"])) {
// triggers even when user enters 0
die("number of children field is empty");
}

isset() checks if the values is set, so it's true even if the value is empty string. Use empty():
if (empty($_POST['email']) == false) {
echo "success!";
}else{
echo "empty!";
}

<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>

try this-
<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>

Null and/or empty strings are still set if the variable is declared.
$_POST contains empty string for your value, and isset() returns true. Use empty() or add != '' in your if condition.try this:
if (!empty($_POST['email']))

Try to use empty() function to check if there is anything in email filed of $_POST array.
The example code based on your code is below:
<?php
if (isset($_POST['email']) && !empty($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>

<?php
if (isset($_POST['email']) && $_POST['email'] != "") {
echo "success!";
}else{
echo "empty!";
}
?>
try this way

Related

Issue comparing values in php

I have this php code meant to compare two values,a variable $rate received from a form which can either have values 'applaud' or 'boo' so I want to check if the value is neither of it and kill the page with an error message.I've tried that but ...localhost can not handle this request
HERE IS MY CODE:
<?php
$rate=$_POST['rate'];
echo $rate;
?>
<?php
if($rate != 'applaud' OR $rate != 'boo')
{
die("Sorry there was a problem var rate was not well stated");
}
else
{
echo 'yay ,well stated!!!';
}
?>
I will apply some useful check to do so:-
<?php
if(!empty($_POST['rate'])){ //check data is coming or not actually
$rate= $_POST['rate'];
if($rate != 'applaud' && $rate != 'boo'){ // use && to check for neither of it
die("Sorry there was a problem var rate was not well stated");
}else{
echo 'yay ,well stated!!!';
}
}else{
die("POST data missing!");
}
?>
Replace OR with && and best way to compare two strings in php is strcmp()
if(strcmp($rate,"applaud")!=0 && strcmp($rate,"boo")!=0)
{
die("Sorry there was a problem var rate was not well stated");
}
If two strings are equal then it will return 0. If you want to learn more about strcmp() then you can visit here

If statement working only until 1st else if [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I am trying to show a different navigation bar depending on a users authority. Only problem is that when i log on to the system it shows the first else if, regardless of the authority of the user. To ensure that the problem is in the loop i have tried switching the else ifs and the same happened. the code is in an external php file and i call the function in the top of each page. any suggestions ?
function checkAuth() {
session_start();
if(!isset($_SESSION['role'])) {
require_once('menu.php');
} else if ($_SESSION['role'] = "registered") {
require_once('regnav.php');
} else if ($_SESSION['role'] = "admin") {
echo "FDGFGFD";
require_once('adminnav.php');
}
}
Your issue is with this part: $_SESSION['role'] = "registered". The single = means you are assigning the value "registered" to variable $_SESSION['role'].
If you are evaluating to check something, you need to use == i.e. $_SESSION['role'] == "registered"
You'll have the same issue with the second elseif
You need to use a double = sign for any condition check. For any condition check in if or else if, you have to use == in the middle of the variables.
If you use only = that means it assigning the value in the $_SESSION['role']. Also you can use === for checking the value as well as the type of the variable.
Valid function is:
function checkAuth()
{
session_start();
if(!isset($_SESSION['role']))
{
require_once('menu.php');
}
else if ($_SESSION['role'] == "registered"){
require_once('regnav.php');
}
else if ($_SESSION['role'] == "admin"){
echo "FDGFGFD";
require_once('adminnav.php');
}
}
?>

Why is $name field never !, even when empty?

I have a basic sign up form, and when checking if a field is not set (if(!$name)) it always goes to 'else', even when the field is empty.
Does anyone know why?
(When i'm trying to check it in reverse (if($name)), it does show the error line. )
*var_dump($name) - always returns a string, never false. I'm guessing thats part of the problem?...
Thanks a lot!!
<?php
$error = '';
if(isset($_POST['submit'])){
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
if( !$name && preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
?>
<form action="" method="post">
<label for="name">Name:</label><br>
<input type="text" name="name"> <br><br>
<input type="submit" name="submit" value="Sign up">
<span class="error"><?= $error ?></span>
</form>
Well, you got wrong IF statement. You are checking if $name is false (it will be only if you send empty string) AND if it's length is between 2-50.
Consider two states:
<?php
$name = 'Login';
$a = !$name; // FALSE! You're variable is OK, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // TRUE! Between 2-50 letters
<?php
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
And second:
$name = '';
$a = !$name; // TRUE! You're variable is empty, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // FALSE! has 0 letters
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
So, you should use OR instead of AND or just forget about first statement (second is checking same thing!):
<?php
if(!preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
You're getting that undefined variable notice because you're trying to echo something in your form that hasn't already been set/not empty and your PHP/HTML form are used in the same file.
Sidenote: <?= is short tag syntax for "echo".
So change:
<?= $error ?>
to and with a conditional statement:
<?php if(!empty($error)) { echo $error; } ?>
or:
<?php if(isset($error)) { echo $error; } ?>
Or use a ternary operator:
http://php.net/manual/en/language.operators.comparison.php
or add an else to my suggestion above.
Plus, you also have a missing brace in your PHP (least, for what you posted) and that alone should have thrown you an unexpected end of file error.
Edit:
The reason that it is failing is the operator you're using, being && (AND). Use || (OR), to check if either one failed the criteria and not both. You're checking if there's no name AND if there's enough valid characters.
if( !$name || preg_match("/^([\w]){2,50}$/", $name))
and that's all it was, a simple wrong choice of operator.
Btw, my edit wasn't based on the other answer given. I actually was busy testing this out when that was posted.
Their explanation is well-written/explained, however they're working too hard.
Changing && to || in your code would have worked just fine.

php and $_GET array

I have submitted some code to the redirected url and now trying to use this to echo some information out but can't figure out where I am going wrong.
I have the following code:
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt) == '1'{
return 'failed';
}
?>
all I want to do is if the url has $login_attempt=1 I want to return the message 'failed' to the page.
There is no point of escaping anything if it doesn't enter anywhere important (like a database).
<?php
if ($_GET['login_attempt'] == '1') {
echo 'failed';
}
?>
Also, you have a problem in your if statement, that's corrected in the code above. Be sure to include all of the condition inside of parenthesis, and not just one side of the equality check.
Also, if you wish to display something on the screen, you should echo it, not return.
how about:
if ($login_attempt == '1'){
echo 'failed';
}
Try this one. Your error in $login_attempt == '1':
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1'){
echo 'failed';
return false;
}
?>
As others already mentioned you have several problems but the syntax error comes from this:
if ($login_attempt) == '1'{
it should be
if ($login_attempt == '1') {
Dont u think if ($login_attempt) == '1' should be something like this ($login_attempt == '1') Sorry...many others also suggested this :P
At the first, I must tell you that you have a mistake in your IF condition. You typed == outside of ().
In addition, you have to be aware of status of setting your variable through your URL. Check the code below. In this code, I made a function to check the status. Default status is true, and we will check it just for a negative condition. I hope it could be useful for you:
<?php
function check() {
if (isset($_GET['login_attempt'])) {
$login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1') {
return false;
} else {
return true;
}
} else {
return true;
}
}
if (!check()) echo('Error Message');
?>

Problem with Boolean Values in PHP

I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.

Categories