if($action == "send"){
$_POST['name'] = $name ;
$_POST['email'] = $email ;
$_POST['phone'] = $phone ;
if(!empty($name) || !empty($email) || !empty($phone)){
.....
} else {
$msg = 'All fields required';
}
//whatever I do only shows $msg.
//already tried that too
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_POST['phone'])){
....
}
What Im trying to do is a form that email me the data, and I want all fields to be filled so maybe Im writing the if statement the wrong way.
sorry if I didnt explained well before.
Your code reads:
If name is not empty, or email is not empty, or phone is not empty
This means that as long as at least one of them are non-empty, then you're good!
Pretty sure that's not what you meant. You want:
If name is not empty, AND email is not empty, AND phone is not empty
Use && instead of || and it should just work!
I think you're getting confused by all the negatives involved here. I suspect what you're after is:
if (!(empty($name) || empty($email) || empty($phone))) {
...
} else {
$msg = 'All fields required';
}
Which would be better written (in my opinion) as:
if (empty($name) || empty($email) || empty($phone)) {
$msg = 'All fields required';
} else {
...
}
if($name=='' || $email=='' || $phone=='')
{
$msg='All fields required';
}
else
{
..............
}
Related
I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.
I'm working on a registration for my classifieds (via a tutorial) but I'm having problems. For some reason, just visiting this page: http://classifieds.your-adrenaline-fix.com/register.php
will generate the 2 custom errors you'll see in a red box above the registration form BUT the form hasn't even been submitted yet so I don't know why this is happening. If anyone could shed some light on this I'd be most appreciative and I thank you all in advance!!
(I've been staring at it for hours)
Here's the code that validates and submits the form data;
<?php
if(empty($_POST) === false) {
$VisitorsFirstName = $_POST['First_Name'];
$VisitorsLastName = $_POST['Last_Name'];
$VisitorsEmail = $_POST['E_mail'];
$VisitorsPassword = $_POST['Pass'];
$RequiredFlds = array('First_Name', 'Last_Name', 'E_mail', 'Pass', 'PassAgain');
foreach($_POST as $key=>$value) {
if(empty($value) && in_array($key, $RequiredFlds) === true) {
$Err[] = 'All Fields Are Required';
break 1;
}
}
if(empty($Err) === true) {
if(email_exists($VisitorsEmail) === true) {
$Err[] = 'The Email Address \''. $VisitorsEmail. '\' Is Already In Use.';
}
if(strlen($VisitorsPassword) < 4) {
$Err[] = 'Please Select A Password of At Least 4 Characters.';
}
if($_POST['Pass'] !== $_POST['PassAgain']) {
$Err[] = 'Passwords Do Not Match.';
}
if(filter_var($VisitorsEmail, FILTER_VALIDATE_EMAIL) === false) {
$Err[] = 'A Valid Email Address is Required';
}
}
}
if(isset($_GET['success']) && empty($_GET['success'])) {
echo 'You Have Now Been Registered and Can Proceed to Creating Your First Ad<br>(Use the Email and Password That You Registered With to Login)';
} else {
if(empty($_POST) === false && empty($Err) === true) {
$register_data = array (
'VisitorsFirstName' => $_POST['First_Name'],
'VisitorsLastName' => $_POST['Last_Name'],
'VisitorsPassword' => $_POST['Pass'],
'VisitorsEmail' => $_POST['E_mail'],
'Notify' => $_POST['Notify']
);
register_func($register_data);
header('Location: register.php?success');
exit();
} else if(empty($Err) === false) {
echo output_error($Err);
}
}
?>
Upon putting just the code you provided on my own server by itself, it works as designed. It isn't running the top block of code, because the $_POST variable is empty. Try outputting the contents of $_POST at the top of the file so you can figure out why it isn't empty.
print_r($_POST);
Try this:
if(!empty($_POST['First_Name']) && !empty($_POST['Last_Name']) && !empty($_POST['E_mail']) && !empty($_POST['Pass'])){
....
}
OR
try isset($_POST['First_Name'])......
This works fine for me!
You could instead check if the submit button was pressed. Like this:
if (isset($_POST['submit']) {
// get the post values
}
This way you could eliminate the script launching before the form was actually submitted. Right now it seems to run as soon as I visit the page.
I'm trying to Validate email twice on a registration form, in order to do it i'm trying to first check that the actual email field isn't empty by running the "empty" function or both of the fields - but for some reason it wont accept it, it complains about unexpected '('
here's the line:
if (empty(($_POST['e-mail']) OR ($_POST['e-mail2']))) {
$error[] = 'Please Enter your Email ';
}
anyone has an idea why i'm getting it and how to fix it ?
Try:
if (empty($_POST['e-mail']) || empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
You might also want to include the isset() function to make sure the POST key is actually set before checking for a value.
Edit
Just for clarity, I'll post an edit here. If you want to validate both the existence of a value, and whether one value for an input equals another, you need to do two sanity checks:
// Check existence of values
if (empty($_POST['e-mail']) || empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
// Check equivalence
if ($_POST['e-mail'] != $_POST['e-mail2']) {
$error[] = 'Your e-mails do not match';
}
You're passing logical expression to empty(), which is obviously wrong
you need to check both variables separately
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
You meant:
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2']))
PHP cannot guess that, it just evaluates your expression like that:
if (empty(($_POST['e-mail']) OR ($_POST['e-mail2'])))
if (empty('value_of_email1' OR 'value_of_email1' ))
if (empty( true ))
if ( false )
if one of the submitted values is truthish (i.e. not-empty), the OR expression still evaluates to true.
I don't think you can use logical expression within an empty() method.
Try separating logical expression to two separate empty() method calls.
Try:
if (empty($_POST['e-mail']) OR empty($_POST['e-mail2'])) {
$error[] = 'Please Enter your Email ';
}
For more information on empty(), take a look at PHP manual on empty().
For posterity...
$email1 = filter_var('aaa#email.com', FILTER_VALIDATE_EMAIL);
$email2 = filter_var('aaa#email.com', FILTER_VALIDATE_EMAIL);
$unmatched1 = filter_var('aaa#emil.com', FILTER_VALIDATE_EMAIL);
$unmatched2 = filter_var('aab#email.com', FILTER_VALIDATE_EMAIL);
$invalid1 = filter_var('aaa.com', FILTER_VALIDATE_EMAIL);
$invalid2 = filter_var('email.com', FILTER_VALIDATE_EMAIL);
$empty = filter_var('', FILTER_VALIDATE_EMAIL);
var_dump(!$email1 || $email1 !== $email2);
var_dump(!$email1 || $email1 !== $unmatched2);
var_dump(!$unmatched1 || $unmatched1 !== $email2);
var_dump(!$email1 || $email1 !== $invalid2);
var_dump(!$invalid1 || $invalid1 !== $email2);
var_dump(!$email1 || $email1 !== $empty);
var_dump(!$empty || $empty !== $email2);
Gives:
bool(false) // Desired in validation...
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
https://ignite.io/code/511f8bf8ec221e7f21000000
So if you replace var_dump with if and simplify e-mail2 (no need to validate):
$email = filter_var($_POST['e-mail'], FILTER_VALIDATE_EMAIL);
if (!$email || $email !== $_POST['e-mail2']) {
// error stuff, including separate check on empty.
}
I have a conditional if check on a webform on which ajax (and php) is doing the submit work.
if(empty($name) or empty($message))
{
do something
}
The above is working if one of the 2 strings is empty.I want to add to the above
or (empty($name) and empty($message))
for checking if both strings are empty but in someway its not working!I want to make sure all 3 senarios are covered,Name empty or Message empty or both empty.
Any ideas?
This will check that both $name and $message is not blank, than true
if($name != '' && $message != '') {
//Do something
}
If you use this, this will check if any 1 field is empty than the condition is true
if($name == '' || $message == '') {
//Do something
}
If you use this, this will be true if both are empty
if($name == '' && $message == '') {
//Do something
}
Replace "or" with "||". Example:
if (empty($name) || empty($message))
{
// Do something
}
or means "If either condition is true", not "If exactly one condition is true".
The code you have already covers your requirement.
I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}