Validate empty field with php - php

I need to validate an empty field with php and javascript, but both of the methods fail.
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress == ''){
echo "";}
else{echo htmlentities($pickupaddress);}?> " id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
//////// Php validation DOES NOT WORK////////
$pickupaddress ='';
$err ='';
$pickupaddress = $_POST['pickupaddress'];
if($pickupaddress == ''){ //if empty field, I also tried == ""
$err.="Please provide pick up address.";
}
///// Javascript validation does not work.
if(form.pickupaddress ==""){
alert("empty address!");
}
//when I click submit nothing happens.
//I am thinking the problem is with
htmlentities($pickupaddress);
//Thanks for your help.

Here is hopefully simpler answer:
$pickupaddress = trim($_POST['pickupaddress']); //trims the string
if (empty($pickupaddress)){ //if empty field
$err.="Please provide pick up address.";
}

On the php side you can try trimming the value and then using empty() on the next line, though that will also invalidate 0, false, null, and other such values. Or you can try using isset.
For the javascript side you can try this function:
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else { return false; }
}
found here: http://www.codetoad.com/javascript/isempty.asp

$cid = $_POST['category'];
if (!empty($_POST['category']))
{
echo "<script>alert('empty field');</script>";
}

Where are you defining pickupaddress? Is it before the form or after? If the variable isn't defined, and depending on your server configuration, the value field of the input could be
Notice: undefined variable pickupaddress
Thus making the value != ''.
View your page source to ensure that the value is indeed empty.

there was a spave " " in your string: echo htmlentities($pickupaddress);}?> "
maybe that was the reason, because it was not an empty string but it was a space?
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress != '') {
echo htmlentities($pickupaddress);
}?>" id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
and i guess you might want to have checked if the post value is set:
if(isset($_POST['pickupaddress'])) {
$pickupaddress = $_POST['pickupaddress'];
}
the php way works for me like that ;) (the message is displayed if i dont write anything)

Related

Testing PHP POST empty values - unexpected result - What am I missing?

I am following a tutorial but I keep getting a TRUE result that shouldn't be correct if I click the submit button WITHOUT filling in any value in the name field.
The first test works as expected, but the second and third test keep returning TRUE when they should return FALSE (leaving the input empty).
What am I missing, not understanding, or doing wrong? This should be simple.
Any help or suggestions are appreciated.
Here is the very simple script:
<?php
//This one works correctly
if(!empty($_POST['name'])) {
echo "There is input here <br>";
} else {
echo "You have not input any info yet. <br>";
}
//This returns true even if I leave the field empty
if(isset($_POST['name'])) {
echo "A name has been input <br>";
} else {
echo "You have not input your name yet. <br>";
}
//This returns true also when it shouldn't
if(filter_has_var(INPUT_POST, 'name')) {
echo $_POST['name'] . ' <- Name Input!<br>';
} else {
echo 'No Name Input.';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="name">Name:</label> <input type="text" name="name"
id="name" size="30" value=""></p>
<p><input type="submit" value="SEND"></p>
</form>
empty does what is says, checks if empty (is empty if not existing aswell)
isset checks if the var exists, no if anything has been set
filter_has_var pretty much the same as isset
place a print_r($_POST) at the top of your file, you will understand :)
You need to check the value to see if it's empty:
if(isset($_POST['name']) && !empty($_POST['name'])) {
http://php.net/manual/en/function.empty.php

Why is the num_tries counter not working?

Hi I am clearing my basics of php and i am kind of stuck in implementing this guess game. My problem is that I want $num_tries to work as a counter and it increases everytime by 1 whenever the user answers incorrectly.
<?php
$target=58;
$message="";
$num_tries=0;
if(isset($_POST["num_tries"])) {
print "set";
++$num_tries;
} else {
print "not set";
$num_tries=0;
}
if (!isset($_POST["guess"])) {
$message="Welcome to the game of Guess!!!!!!";
} elseif($_POST["guess"]> $target) {
$message= "Try a smaller Number";
} elseif($_POST["guess"] < $target) {
$message= "Try a larger Number";
} else {
$message= "congrats....You got it.";
}
?>
<HTML>
<HEAD><TITLE>Guess Game</TITLE>
</HEAD>
<BODY>
<H1><?php print $message ?></H1>
Guess Number:<?php print $num_tries ?>
<FORM action="<?php print $_SERVER['PHP_SELF'];?>" method="POST">
<INPUT type="text" name="guess">
<INPUT type="hidden" name="num_tries" value="<?php $num_tries?>">
</FORM>
</BODY>
</HTML>
You can solve it in your first lines:
$target=58;
$message="";
$num_tries = (!empty($_POST['num_tries']) ? $_POST['num_tries'] : 0);
That means if the form is not submitted before, $num_tries will be zero, otherwise, the value will be the last submitted value.
And then you need to print in the hidden element
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries?>">
---------------------------------------------------^^^^
$message="";
$num_tries=0;
change the above declaration to $num_tries=isset($_POST["num_tries"]) ? $_POST["num_tries"] : 0; which means if the post var value is set, then assign post var value, else assign 0.
and next change what you need to make is printing the value under hidden element.
you can use print or print_r or echo.
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries; ?>">
You are using <?php $num_tries ?> which literally does nothing.
You need to use <?php echo $num_tries ?> (print also works, but for your use case, echo is more efficient) in order to actually place the value into the form.
Additionally, $num_tries = 0; will not bother reading the existing value. You can use $num_tries = $_POST['num_tries'] | 0; although it will generate a PHP notice when the field isn't set, if you care about this, use isset with a ternary operator or if/else.

Using isset or is not set with variable in PHP?

I have a form which submits data, and as a test I am attempting to first check if a variable is set on submit. If the variable is set, a text will be displayed stating something like "Variable is set". However if it isn't set, a text will be displayed saying "variable not set", once the variable hasn't been set it should then be set so next time when the form is submitted it displays variable is set however this is not working for me, for some reason it always displays that the variable is not set, my PHP code will be below:
<?php
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
I feel really stupid for not being able to do something which seems so easy, I am only just learning and sort of trying to teach myself, thank you for any help provided!!!
Working code and explanation:
<?php
$test="";
if (isset($_POST["text"])) { //always directly check $_POST,$_GET var without assigning
echo "This var is set";
$test=$_POST["text"]; // then assign
}
else{ // and use else clause for otherwise case
echo "This var is not set";
$test = 'set'; // AND if you want set to default/custom value in case of not set.
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off">
<br /><br />
<input type="submit" value="submit">
</form>
If you are using form to submit values, then try this one,
if (isset($_POST['text'])) {
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
Otherwise, If a variable set to empty value like $test = '';
(It means variable is set but it has no values) It will execute your first if condition only.
<?php
$test=$_GET["text"];
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="#" method="get">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
You haven't declared the variable $test.
Unless you've still got a bit of PHP somewhere that you haven't included here, your variable is empty. When a form is submitted, the input will be added to either the $_POST array (for method = "post") or else the $_GET array (for method = "get").
To Fix:
<?php
if (isset($_POST['text'])) {
$test = $_POST['text'];
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>

php if elseif then what?

This is my PHP code
The problem points I have mentioned in comments inside the code portion
if(isset($_POST['submit']))
{
if(isset($_POST['rdoption1']))
{
$var1 = $_POST["rdoption1"];
}
if(isset($_POST['rdoption2']))
{
$var2 = $_POST["rdoption2"];
}
if(!isset($_POST['rdoption1']))
{
$message = "Please select Option1";
}
elseif(!isset($_POST['rdoption2']))
{
$message = "Please select Option2";
}
elseif($_POST['rdoption2'] == "checkSetXY")
{
if($_POST["valXLocation"] == "")
{
$message = "You forget to enter X value.";
}
elseif($_POST["valYLocation"] == "")
{
$message = "You forget to enter Y value.";
}
} // till here all is good. I get all error messages if anything is left vacant or not clicked on radio button
elseif(empty($_POST['txtoption3'])) //this is not working //the issue is if i select rdoption1 any option and rdoption2 checkDefault next code logic work.. but next code logic does not work when i click on the radio of checkSetXY and enter x and y values.. It simply does not execute code further..
{
$message = "Please enter your name.";
}
else
{
//insert into db
}
}
This is html form with PHP echos
Here I'm getting messages where they shall be but not when I select checkSetXY value
<?php if(!empty($message)){ echo $message; } ?>
<form id="form1" name="form1" method="post" action="form1.php">
Space portion:
<input type="radio" name="rdoption1" value="RJ"/>space 1
<input type="radio" name="rdoption1" value="SM" />space 2
Pixel Location
<div class="formText">
<input type="radio" name="rdoption2" value="checkSetXY"/> Specify Location
X: <input type="text" id="locField" name="valXLocation">
Y: <input type="text" id="locField" name="valYLocation">
<input type="radio" name="rdoption2" value="checkDefault"/>Default
<input type="text" class="input" name="txtoption3">
<input type="submit" name="submit" value="Submit">
</form>
Now I'm confused why is it not taking elseif of txtoption3
Any help? Thanks in advance
That won't work because, it will be always set. So, use empty();
elseif(empty($_POST['txtoption3'])) //this is not working
Explanation
You are posting a form input. When you send it without filling anything, it just sends this value. ""
An empty string is not equal to null or not set.
Also, as Peter Szymkowski said, check out the fiddle.
Textfields are set if they are empty. You have to check with empty($_POST['txtoption3']) .
that is the else for
if($_POST['rdoption2'] == "checkSetXY")
which I guess is true so it will not go into that else

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

Categories