Obviously I know that array_key_exists is not giving a false positive. I'm doing something wrong. I just wanted to grab your attention. :)
Seriously though. I am doing this as an exercise.
Here is my code:
<?php
$error = "";
if($_POST)
{
if (!array_key_exists('email',$_POST)) {
$error .= "<p>You did not submit an e-mail address. Please try again.</p>";
}
if (!array_key_exists('password',$_POST)) {
$error .= "<p>You did not submit a password. Please try again.</p>";
}
echo $error;
print_r($_POST);
}
?>
When I don't submit either email or password, echo $error outputs nothing. print_r($_POST) outputs whatever I sent.
What am I missing here?
$_POST['email'] and ['password'] exist but are empty you should see it with your print_r($_POST);
You should check the value instead of the key.
I think that you should use
empty($_POST['email'])
instead of array_key_exists.
Why not just check empty($_POST['email']) instead of !array_key_exists?
Both will check if the key exists and also will check if they are not NULL.
empty will additionally check if it's no empty array, 0(as int and as string), empty string, etc.
EDIT
I was late
I would add a hidden input to your form
<input type="hidden" name="formSubmitted" value="1" />
Then you can check for the form having been submitted, rather than checking for the existence of your $_POST array. Also, in case both of your fields are empty when they are submitted, this provides a separate mechanism for identifying that, rather than assuming both of your fields will be valid.
<?php
$error = "";
if(isset($_POST['formSubmitted']) && $_POST['formSubmitted'] == 1) {
if (!array_key_exists('email',$_POST)) {
$error .= "<p>You did not submit an e-mail address. Please try again.</p>";
}
if (!array_key_exists('password',$_POST)) {
$error .= "<p>You did not submit a password. Please try again.</p>";
}
echo $error;
print_r($_POST);
}
?>
I'm also assuming you (will) have some other forms of validation to ensure that the email address and password meet some basic requirements that are not shown here.
Related
I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.
I am adding a contact page to my website, but having issues with the comment text box. When the user enters invalid information into the name and email text field, the website redirects the user back to the contact page to fill out the correct information. However, I want the comment box to be optional for the user. For example, the user will enter their name and email, but doesn't have any comments. The code should then process the information. Currently, my code will redirect the user back to the contact page because the user did not enter any information into the comment box. Any suggestions on how to fix this error?
Thanks!
if (empty($_REQUEST['comment'])) {
$error = TRUE;
} else {
$comment = $_REQUEST['comment'];
$form['comment'] = $comment;
if (!preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
}
If you want to allow the content box to be empty, just let an empty value be an acceptable value. This means only running your validation against that field if there is a value present. This means removing your if/else statement since empty($_REQUEST['comment']) is no longer a valid check.
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
I just added !empty($comment) && to your check which basically says, "if there is a value go ahead and validate it".
One thing you should also do if you use this code is trim whitespace from your comment box values. Otherwise a user could type a space character and that would not be considered empty:
$comment = trim($_REQUEST['comment']);
Final code:
$comment = trim($_REQUEST['comment']);
$form['comment'] = $comment; // I am assuming this is used elsewhere
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
I am making a login system and I have a form with some validation.
However my form seems to be failing to pass the validation even though the data input should pass easily.
See:
http://marmiteontoast.co.uk/fyp/login-register/index.php
When you input a username, it should be over 3 characters. But even if you enter one really long you get the error message: The username is less than 3 characters.
EDIT: There was an issue in my copying from formatting that caused a missing }. I've corrected this. It wasn't the issue.
This is the if statement for the username pass. So it seems like it is not getting past the first test:
if (isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
$_SESSION['status']['register']['username'] = $username;
if(strlen($username) > 3){
if(strlen($username) < 31){
if(user_exists($username) === true){
$_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
}else{
// passed
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is not entered.';
}
And this is the HTML for the username:
<form method="post" action="register.php">
<div class="username">
<label class="control-label" for="inputUser">Username</label>
<input type="text" id="inputUser" name="username" placeholder="Username" value="<?php echo $usern_value; ?>" />
</div>
You can see the site here: http://marmiteontoast.co.uk/fyp/login-register/index.php
Session
The index page does use sessions.
It starts with this:
<?php
session_start();
?>
And kills the session at the end of the file:
<?php
unset($_SESSION['status']);
?>
But in the file it starts new sessions which store the inputs. This is so if you make a mistake, it still holds your info so you can adjust it rather than having the fill in the form again. Here is an example of where it grabs the username and saves it, then outputs it.
<?php
if(isset($_SESSION['status']['register']['username'])){
$usern_value = $_SESSION['status']['register']['username'];
} else {
$usern_value = "";
}
?>
value="<?php echo $usern_value; ?>" />
This is the user-exists function:
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
Ah, I can see the problem from your website link. When the error pops up ("The username is less than 3 characters."), try refreshing your browser. I expected to receive a browser warning that says the data would be resubmitted to the server — because you are in a post form — but I did not.
So, what does this mean? It means that immediately after validation failure, you are redirecting back to the same screen, and — unless you are using a session to preserve this information — your $_POST data will be lost. Commonly in the case of validation failure with this sort of form, you must prevent that redirect and render inside the post operation, which keeps the user's input available to you. The redirect should only occur if the form input was successful (i.e. it saves to the data and/or sends an email).
Edit: I should have seen the $_SESSION in the original post. OK, so the strategy is to write things to the session, redirect regardless of validation outcome, and to save error messages to the session. I wonder whether you are not resetting the session errors array when you're posting the form? Immediately after your first if, try adding this:
if (isset($_POST['username'])){
$_SESSION['status']['register']['error'] = array(); // New line
Unless you have something to make the session forget your errors, they will be stored until you delete your browser's cookie.
You have missed a closing brace } on this line:
if(user_exists($username) === true){
} else{// **missed the closing brace before the else**
// passed
}
Why is your logic so complex?
if (strlen($username) < 3) {
// too short
} elseif (strlen($username) > 31) {
// too long
} elseif (true === user_exists($username)) {
// already registered
} else {
// passed
}
I'm giving this simple html form with password and with php I'm giving to do this
The only valid password shall be "testing" (without the quotes). If the user did not type a password, give them a warning to "Please type a password" and do no more processing on the data at all. If the user did not type the valid password "testing" (without the quotes), then tell the user "Invalid password, sorry" and do no more processing on the data at all. (Use an “if” statement to find out if they entered a password, etc…)
but I just can't seem to figure out
can someone give me a hand?
the html coding is
<form action = "lab.php" method = "post" name = "lab_form">
what is your last name: <input type = "text" name = "last"><br />
what is your student number (password): <input type = "password" name = "number">
</form>
what I did with my php is this....but didn't work at all...and all I've learned is $_POST and isset for now. I wonder how I can get this done with $_POST, isset and with if statement...
<?php
echo $_POST["last"] . "<br/>";
if (isset($_POST["number"]))
{
echo "The variable $_POST[number] exists.";
}
else if (!(isset($_POST["number"])))
{
echo "Please enter a password.";
}
else
{
echo "No variable called $_POST[number]";
}
?>
I know what I'm doing wouldn't make must sense....but...ya :(
Thanks in advance though ^_^
P.S. I know in the php code I should add something like
if($_POST["number"] == testing)
and continuing on but the thing is I couldn't even make it show the other parts so i didn't bother try the "testing" as password yet.
Small mistake. Use empty() too.
<?php
echo $_POST["last"] . "<br/>";
if (isset($_POST["number"]))
{
echo "The variable $_POST[number] exists.";
}
elseif (empty($_POST["number"]))
{
echo "Please enter a password.";
}
elseif (!isset($_POST["number"]))
{
echo "No variable called $_POST[number]";
}
?>
I have a rough php script that sees if a user has filled in the html form input after they have clicked submit. I am having a problem with getting isset() and is_string() to work. If I use isset() the form is emailed even if the form inputs are left blank, is_string() throws an error messages even if the form input are filled in. I have tried !isset() and that still sends blank input. The only thing working is if I use == NULL. At this moment in time I am not going to validate the input as I am trying to understand why this isn't working as I am pretty new to PHP.
$subject = "Feedback from Your Website.";
$email = ($_POST['email']);
$name = ($_POST['name']);
$message = ($_POST['feedback']);
if (isset($_POST["name"]))
{
//send message
mail($subject, $name, $email, $message);
}
else
{
//error message
echo "Please do not miss out any fields";
}
I also tried:
if (isset($_POST["name"], $_POST['email']))
{ }
if (isset($name, $email))
{ }
if (is_string($name || $email))
{ }
But all failed, so far all that's working is:
if ($name == NULL || $email == NULL || $message == NULL)
{ }
Thank you in advance.
Try to use empty(). This function return TRUE if a variabile is empty or non set, FALSE otherwise.
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["feedback"]))
{
//error message
echo "Please do not miss out any fields";
}
else
{
//send message
mail($subject, $name, $email, $message);
}
is_string($name || $email) is not working because $name || $email is cast to a boolean and a boolean is not a string.
isset() function will return a True value after your form submitting. Actually, your field has been sent to your target file. So your code will send emmial. For what you need, you must use the code below:
if (isset($_POST["name"]) && $_POST["name"] != '') {
// do something
}
isset checks if value is created in the array. It IS going to be there always as the form always have the same fields, empty or not. You need to check their content
isset() returns true because $_POST['email'] has been set. It simply is empty. Since you submit the form all the variables of the form have been set.
You have to write this
if (isset($_POST["email"]) && $_POST["email"] != '')
How about empty( ) you can check the details of the function in te php manual .