I have this PHP code which should return only either true or false after running multiple stored functions, but unfortunately it does not work as expected.
I firstly check the email validation and return true if valid and false if invalid, then i am doing the same for username.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
I need to return only False or True after checking both.
I know that it is very small trick but i could not get it.
Try this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else { $valid=false; }
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
} else { $valid=false; } //and between the last $valid value
}
or again this:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Email is valid
if(checkmail($_POST['email'])) {
$_SESSION['v_mail'] = $_POST['email'];
$valid = true;} else {
$valid=false; return} //exit from the function if valid is false
// username is valid
if(checkuser($_POST['username'],5,10)) {
$_SESSION['v_username'] = $_POST['username'];
$valid=true;} else { $valid=false; }
}
if(checkmail($_POST['email']) && checkuser($_POST['username'],5,10)) {
$_SESSION['v_mail'] = $_POST['email'];
$_SESSION['v_username'] = $_POST['username'];
$valid = true;
} else {
$valid = false;
}
Sorry was tired missed part of the code, however I would approach this problem little bit differently:
$isMail = (checkmail($_POST['email'])) ? $_SESSION['v_mail'] = $_POST['email'] : false;
$isUser = (checkuser($_POST['username'],5,10)) ? $_SESSION['v_username'] = $_POST['username'] : false;
$valid = $isMail && $isUser;
Or move $_SESSION variables to checkmail, checkuser functions and then simply $valid = checkmail($_POST['email']) && checkuser($_POST['username'],5,10)
Related
For my website i want to have registration. And everything goes well until it's time for validation. So, i have to this all in different files (validation in validation.php, registration in registration.php and registration form in registrationForm.php). In registration.php i have something like this:
<?php
session_start();
include 'validation.php';
include "mail.php";
include 'dbConnection/dbconn.php';
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
//sendMail("test", "test");
if (validateName($name) && validateSurname($surname) && validateEmail($email) && validatePassword($password1) && validateUsername($username) && checkIfPasswordsAreMatching($password1, $password2)) {
echo "Worked";
} else {
echo "Not worked";
header("Location: registrationForm.php");
}
} else {
header("Location: registrationForm.php");
}
?>
And my problem is that no matter if i put good data or completely wrong data my validation always says that it's wrong.
Here is my validation code (validation.php):
<?php
session_start();
$allChecked = true;
function validateName($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['nameError'] = "Your name cannot contain any special character.";
}
return $string;
}
function validatePassword($string) {
if (strlen($string) < 8 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must be between 8 and 20 characters long.";
}
if (preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]/', $string) == false) {
$allChecked = false;
$_SESSION['passwordError'] = "Your password must contain at least 1 big letter, 1 special character, 1 number and 1 small letter.";
}
return $string;
}
function validateSurname($string) {
if (strlen($string) < 2) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname is too short. It has to be at least 2 characters long.";
}
if (preg_match('[\W]', $string)) {
$allChecked = false;
$_SESSION['surnameError'] = "Your surname cannot contain any special character.";
}
return $string;
}
function validateUsername($string) {
if (strlen($string) < 2 || strlen($string) > 20) {
$allChecked = false;
$_SESSION['usernameError'] = "Your username must be between 2 and 20 characters";
}
/*
$sql = "SELECT * FROM Users WHERE username = '$string'";
$sql = $conn->query($sql);
$nameExists = $result->fetch();
if($nameExists) {
$allChecked = false;
$_SESSION['usernameError'] = "Name is already taken";
}
*/
return $string;
}
function validateEmail($string) {
$em = filter_var($string, FILTER_VALIDATE_EMAIL);
if (!$em){
$allChecked = false;
$_SESSION['emailError'] = "Your email has to be valid.";
}
/*
$sql = "SELECT * FROM Users WHERE mail = '$string'";
$result = $conn->query($sql);
$emailExists = $result->fetch();
if($emailExists) {
$allChecked = false;
$_SESSION['emailError'] = "Email is already taken";
}
*/
return $allChecked;
}
function checkIfPasswordsAreMatching($password1, $password2) {
if ($password2 != $password1) {
$allChecked = false;
$_SESSION['passwordError'] = "Passwords must be the same";
}
return $allChecked;
}
?>
In each of your return statements check $allChecked and if it has NOT been set return true instead of $allChecked.
return (isset($allChecked) ? $allChecked : true);
In your functions validateName, validateSurname, validatePassword, validateUsername you are returning the original string instead of validation result. In validateEmail and checkIfPasswordsAreMatching you are returning $allChecked but it's not initialized with value if all checks are passed so null is returned instead.
You should rewrite your validation functions to look like this
function validateName($string) {
if (strlen($string) < 2) {
$_SESSION['nameError'] = "Your name is too short. It has to be at least 2 characters long.";
return false;
}
if (preg_match('[\W]', $string)) {
$_SESSION['nameError'] = "Your name cannot contain any special character.";
return false;
}
return true;
}
How do i restrict my sign up to people with a specific email domain in PHP
So for example, only people with a '#amn.com' email address can register
Use the following regular expression:
<?php
$email = "mytestemail#amn.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Not a valid e-mail address!");
} else {
if(empty(preg_match("/#amn.com$/", $email))) {
die("E-mail must end with #amn.com!");
} else {
//valid//
}
}
?>
<?php
$email = $_POST['email'];
$domain = explode('#',$email)[1];
if($domain != 'amn.com')
{
die('This domain is not allowed to register')
}
On your server, check the mail input field if it contains the string and ends with it, like this:
$email = $_POST['email'];
$domain = explode('#',$email)[1];
$emailErr = '';
$domain = explode('#',$email)[1];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $domain != 'amn.com') {
$emailErr = "Invalid email";
} else {
//valid - use input
}
For js validation, you can use something like this:
function validateEmail(email)
{
var splitted = email.match("^(.+)#thisdomainonly\.com$");
if (splitted == null) return false;
if (splitted[1] != null)
{
var regexp_user = /^\"?[\w-_\.]*\"?$/;
if (splitted[1].match(regexp_user) == null) return false;
return true;
}
return false;
}
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!
}
}
I need to create very simple register/login system in PHP. User details must be stored in array in txt file. For some reasons even when PHP not show any error details are not saved to txt file. Any hint?
$fullname='';
$email ='';
$username ='';
$password = '';
$error = '';
$form_is_submitted = false;
$errors_detected = false;
$clean = array();
$errors = array();
if (isset($_POST['submit'])) {
$form_is_submitted = true;
if (ctype_alnum ($_POST['fullname'])) {
$clean['fullname'] = $_POST['fullname'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your Full Name!';
}
if (ctype_alnum ($_POST['email'])) {
$clean['email'] = $_POST['email'];
} else {
$errors_detected = true;
$errors[] = 'You have enter an invalid e-mail address. Please, try again!';
}
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
if ($form_is_submitted === true
&& $errors_detected === false) {
$fp = fopen('filewriting.txt', 'w');
fwrite($fp, print_r($clean, TRUE));
fclose($fp);
} else {
echo $errors;
}
There are a few things wrong with your code.
There is a missing brace for
if (isset($_POST['submit'])) {$form_is_submitted = true;
so it needs to read as
if (isset($_POST['submit'])) {
$form_is_submitted = true;
}
You are using ctype_alnum so when it comes to an email address, the # and the dot do not count as alpha-numerical characters a-z A-Z 0-9; either remove it if(ctype_alnum ($_POST['email'])) which proved to be successful in testing this.
You can also use another function such as FILTER_VALIDATE_EMAIL
I quote from the PHP manual:
Return Values
Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
This block has a misplaced brace
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
Which should read as
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
} // was missing
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
// } // was misplaced - commented out to show you
otherwise it would not have written the password (as part of the array) to file.
Plus this $error = ''; should "probably" read as $errors = ''; but that didn't stop it from writing the data to file.
As for the Array message, remove the square brackets [] from all instances of $errors[]
I think
fwrite($fp, print_r($clean, TRUE));
should be
fwrite($fp, $clean, TRUE);
or
file_put_contents($fp, $clean);
$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>';
}