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.
Related
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.
I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.
What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}
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 .
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/