I'm confused how to use isset and empty, I'm trying to write a simple api, there should be error saying which param is missing and return error too if the param is null.
What's wrong my statement below?
$email= isset($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
if(empty($email)) {
echo 'email cannot be empty!'
}
You don't actually need to use both isset and empty, because empty already does it.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
More details are here:
http://php.net/manual/en/function.empty.php
So your code could look this way, for example:
if (empty(trim($_POST['email']))) {
echo "Email cannot be empty!\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = trim($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Your email {$email} is invalid\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = mysqli_real_escape_string($email);
Change $email to :
$email= isset($_POST['email']) && !empty($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
So the $_POST['email'] is not containing empty value.
Try to use next code snippet
if( false === input_filter(INPUT_POST, FILTER_VALIDATE_EMAIL) ) {
echo "error message";
}
$email = input_filter(INPUT_POST, FILTER_SANITIZE_EMAIL );
// to do somethink with email...
I think you are trying to check $email value which is null. You should check $fname in if statement instead.
try this to check for all missing fields:
$required_fields = array('email', 'name', 'password');
$err_msgs=array();
foreach($required_fields as $field) {
if(empty( $_POST[$field]) ){
err_msgs[]= $field . ' cannot be empty!';
}
}
if (!empty($err_msgs)) {
echo json_decode($err_msgs);
}
Edit: removed isset() after reading Axalix's answer.
Related
I've tried all the other answers for my query on here and none of them suited my needs. I'm on PHP 5.2, and I'm starting to think that maybe this filter doesn't work on my version? I've added code below, let me know if you see anything. I've tried it with and without sanitizing, and every time it just skips over the entire clause and submits the form to the database.
if(isset($_POST['fname']) && !empty($_POST['fname']) AND isset($_POST['lname']) && !empty($_POST['lname']) AND isset($_POST['college']) && !empty($_POST['college']) AND isset($_POST['address']) && !empty($_POST['address']) AND isset($_POST['username']) && !empty($_POST['username']) AND isset($_POST['password']) && !empty($_POST['password']) AND $passwordEmail == $password2){
$address = $_POST['address'];
$address = filter_var($address, FILTER_SANITIZE_EMAIL);
if(!filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
header("location: registration.php?remarks=successEmail&college=$college&fname=$fname&lname=$lname&contact=$contact&username=$username");
}
else{
header("location: registration.php?remarks=failedEmail&college=$college&fname=$fname&lname=$lname&contact=$contact&username=$username");
}
Edit:
I removed the duplicate function and the ! and it still does not work.
The only addition was the moving of the '!' and the removal of the first filter.
This is the code I am now using which is still failing and taken from some of the answers given:
if(isset($_POST['fname']) && !empty($_POST['fname']) AND isset($_POST['lname']) && !empty($_POST['lname']) AND isset($_POST['college']) && !empty($_POST['college']) AND isset($_POST['address']) && !empty($_POST['address']) AND isset($_POST['username']) && !empty($_POST['username']) AND isset($_POST['password']) && !empty($_POST['password']) AND $passwordEmail == $password2){
$address = $_POST['address'];
if(filter_var($address, FILTER_VALIDATE_EMAIL) != false) {
header("location: registration.php?remarks=successEmail&college=$college&fname=$fname&lname=$lname&contact=$contact&username=$username");
}
else{
header("location: registration.php?remarks=failedEmail&college=$college&fname=$fname&lname=$lname&contact=$contact&username=$username");
}
Final Edit: I copied this example I found and just changed the variable names and now it works.
<?php
$email = "john.doe#example.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Your ! is in the wrong place.
if(filter_var($address, FILTER_VALIDATE_EMAIL) !== false) {
By putting it before the function name you are saying "if the opposite of the return value of filter_var() is equal to false and the same type". That gives you true === false which of course is false.
What you really mean is "if the return value of filter_var() is equal to false and the same type". That gives you true !== false which is of course true.
Or simplify it:
if(filter_var($address, FILTER_VALIDATE_EMAIL)) {
You are using filter_var TWICE thats why it will always fail doing this
if(!filter_var($address, FILTER_VALIDATE_EMAIL) === false) {
The variable $address has already been modified to a boolean value in the line before:
$address = filter_var($address, FILTER_SANITIZE_EMAIL);
$address has the false or true value instead of the email string!
Oh, and of course, like John Conde said, you're using the ! in the wrong place.
I had the same problem. What I found out was that the else was below the }. When I moved it right behind the } the validation worked.
Wrong code:
if(filter_var($em, FILTER_VALIDATE_EMAIL)){
$em = filter_var($em, FILTER_VALIDATE_EMAIL);
}
else{
echo "Invalid email format";
}
Working code:
if(filter_var($em, FILTER_VALIDATE_EMAIL)){
$em = filter_var($em, FILTER_VALIDATE_EMAIL);
//Check if email already exists
}else{
echo "Invalid email format";
}
I need to change the value of the variable $destination to help validate a form. If none of the fields within the form, the page refreshes with the error message displayed, which works. If the fields are all filled in, the the $destination value should change and the message 'it works!' is printed. However, if all fields are filled in and the user submits the form, the message 'it works!' is printed, but the $destination's value is still set to 'this-page'. What am I missing here?
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!$fname OR !$lname OR !$email OR !$phone) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Hope this is academic. There are better ways to approach this. But here:
$destination = '';
$fname = isset($_POST['fname']) ? $_POST['fname'] : null ;
$lname = isset($_POST['lname']) ? $_POST['lname'] : null ;
$phone = isset($_POST['phone']) ? $_POST['phone'] : null ;
$email = isset($_POST['email']) ? $_POST['email'] : null ;
if (empty($fname) || empty($lname) || empty($phone) || empty($email)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
} else {
print 'It works!';
$destination = 'results-page';
}
Someday take a look at some PHP frameworks and how they handle form validation. for example: http://framework.zend.com/manual/1.12/en/zend.form.elements.html Might give you some insight.
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!empty($fname) || !empty($lname) || !empty($email) OR !empty($phone)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Seems like the problems isn't related to the validation part here. You are getting both the print from the else statement and the $destination variable from the if statement? That should be logically impossible. Are you sure you don't have any syntax errors etc. in your code? Is that the exact code you have in your program?
I am looking for email in my view page. there are two ways email can get there. Either by POST or by SESSION.
if it is a $_POST then I want to use the $_POST email other wise I want to use the email saved in session.
Currently the code I have is below
$email = (isset($_POST['email']) ? $_POST['email'] : '');
whats the BEST way to do it in least lines of code
I'm guessing you're just looking for this (assuming the email address is stored in the $_SESSION array under the key email):
$email = (isset($_POST['email']) ? $_POST['email'] : $_SESSION['email']);
Or am I misunderstanding your question?
Try this:
$email = (isset($_POST['email']) ? $_POST['email'] : (isset($_SESSION['email'])) ? $_SESSION['email'] : '');
Which is the same of:
if(isset($_POST['email'])) {
$email = $_POST['email'];
} else {
if(isset($_SESSION['email'])) {
$email = $_SESSION['email'];
} else {
$email = '';
}
}
A funny alternative to the correct answer of #Gabriel Santos
$input = function($param, $default = '') {
static $input;
if (null === $input) {
$input = array_merge($_SESSION, $_POST);
}
return isset($input[$param]) ? $input[$param] : $default;
};
// get input
$email = $input('asd');
This if statement is not working. I am trying to make it so that all the things must contain a value for the first statement to be shown, but it works when only one value is selected.
<?php
if ((isset($_POST["FirstName"]))&&(isset($_POST['SecondName']))
&&(isset($_POST['email']))&&(isset($_POST["submit"]))) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
Even if the input is not filled it will be set. you need to check if it is set and if it contains input.
Try making a function to do just that:
function issetWithInput(&$va){
return (isset($va) && !empty($va));
//checks that it is set and contains input.
}
Then you can do something like:
if(issetWithInput($_POST["FirstName"])&&issetWithInput($_POST['SecondName'])..) {
Try this
<?php
if (isset($_POST['FirstName']) &&
isset($_POST['SecondName']) &&
isset($_POST['email']) &&
isset($_POST['submit']) &&
!empty($_POST['SecondName']) &&
!empty($_POST['FirstName']) &&
!empty($_POST['email'])) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
this is what i do when checking my form
<?php
$firstname= $_POST['FirstName'];
$secondname = $_POST['SecondName'];
$email = $_POST['email'];
$submit = $_POST['submit'];
if ($submit)
{
if ($firstname&&$secondname&&$email)
{
echo "You've given all your details";
}
else
echo "Please enter all your details";
}
?>
but i may have miss understood what you are tying to do :), please do ignore this if this makes no sense at all (im still rather new to php)
$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}