FILTER_VALIDATE_EMAIL not working - php

I certainly must be missing something here. For some reason filter_var is not working. I'm trying to validate an email from $_POST, and it returns false even with valid emails. But, when I hardcode an email, it works fine. What's wrong?
Here's my php code:
function redirect() { //redirecting to home page function. Used in one of the lectures.
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/index.php");
exit;
}
try
{
$dbh = new PDO($db, $dbuser, $dbpassword);
}
catch (PDOException $e)
{
echo "Connection failure: " . $e->getmessage();
}
if (!isset($_POST['email']) || !isset($_POST['password1']) || !isset($_POST['password2'])) {
redirect();
}
$password1 = htmlspecialchars($_POST['password1']);
$email = htmlspecialchars($_POST['email']);
$password2 = htmlspecialchars($_POST['password2']);
//preg_match('/.+#.+\./', $email) == FALSE
if ($email = "") {
print "email not there";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "not real email";
} elseif (strlen($password1) < 6) {
print("password too small");
} elseif (!(preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $password1))) {
print "numbers and letters plz";
} elseif ($password1 != $password2) {
print "passwords not same";
//redirect();
}

Change the first email check:
if ($email == "") {
print "email not there";
}
It is getting the value " instead of checking for it.

Related

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

PDOException: in C:\wamp64\www\Fireblock\index.php on line 3

Help i wanna make a register system but when i try to access the page on localhost it say me this :
Fatal error: in C:\wamp64\www\Fireblock\index.php on line 3
PDOException: in C:\wamp64\www\Fireblock\index.php on line 3
Idk what's wrong in line 3 since i was following a tutorial oof
My php script :
<?php
try {
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock;', 'root', ''); //where is the error
if (isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = password_hash($_POST['password']);
$pass2 = password_hash($_POST['password2']);
if (!empty($_POST['username']) AND !empty($_POST['password']) AND !empty($_POST['password2'])) {
$usernamelength = strlen($username);
if ($usernamelength <= 255) {
if ($email == $email2) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if ($password == $password2) {
$insertmember = $bdd->prepare("INSERT into members(username, email, password) VALUES(?, ?, ?)");
$insertmember->execute(array(
$username,
$email,
$password
));
$error = "Your account has been created!";
} else {
$error = "Your passwords aren't the same!";
}
} else {
$error = "Your email address isn't valid!";
}
} else {
$error = "Your emails aren't the same!";
}
} else {
$error = "Your username can't be higher than 255 characters!";
}
} else {
$error = "Every fields should be completed!";
}
}
} catch (PDOException $ex) {
print $ex->getMessage();
}
?>
I putted all the PHP part
Try
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
i have removed a semi-colon at the end of the last key/value pair (after fireblock) as it is not used in any code examples i used for comparrison with your code.

PHP Sign-up Form Issues with Validation and Insertion

I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.

how to validate one variable either of two variables in php

i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure

How to put my validation block of codes into Function PHP

How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}

Categories