So I have a form and need to validate it. So what I'm doing is
if(empty($name) || empty($username) || empty($email) || empty($password)){
$_SESSION['comp_form'] = "Complete all fields";
header('Location: register.php');
}
if(strlen($password) < 5){
$_SESSION['pass_leng'] = "Choose a longer password";
header('Location: register.php');
}
I'm doing this because I need to display the Session on another page, but only one error gets shown. What I'm trying to do is something like this where all errors are shown at once.
Am I on the right track? Or is there another way to go about this. Because I can only display one message at a time using
$_SESSION['comp_form'] = "Complete all fields";
header('Location: register.php');
exit()
You can build up an array of errors during your validation, then check to see if there are errors in the array and redirect if there is. You could also use array keys to identify which field to show each error on.
Here's an example:
$errors = array();
if(empty($name) || empty($username) || empty($email) || empty($password)){
$errors['comp_form'] = "Complete all fields";
}
if(strlen($password) < 5){
$errors['pass_leng'] = "Choose a longer password";
}
// more validation here if you wish
if(count($errors) > 0) {
$_SESSION['errors'] = $errors;
header("Location: register.php");
exit;
} else {
// clean up previous validation errors, everything's fine
unset($_SESSION['errors']);
}
Then on your form you can check for errors:
<!-- add hasError class to input when validation failed to allow you to style it -->
<input type="password" name="password" class="<?php if(isset($_SESSION['errors']['pass_leng'])) echo 'hasError'; ?>">
<!-- if there's an error, output it on a generic error message element -->
<?php if(isset($_SESSION['errors']['pass_leng'])) echo '<p class="formError">' . $_SESSION['errors']['pass_leng'] . '</p>'; ?>
You could try something like this:
$_SESSION['error'] = 0;
if(empty($name) || empty($username) || empty($email) || empty($password)){
$_SESSION['comp_form'] = "Complete all fields";
$_SESSION['error'] = 1;
}
if(strlen($password) < 5){
$_SESSION['pass_leng'] = "Choose a longer password";
$_SESSION['error'] = 1;
}
if($_SESSION['error'] == 1){
header('Location: register.php');
}
Just unless you want to use AJAX which will improve the smoothness of your Site at the cost of using JavaScript.
Create an array of fields you require to be validated (which match up with their $_POST names):
$fields = array(
'name' => 'Name',
'username' => 'Username',
'email' => 'E-Mail',
'password' => 'Password'
);
Then loop over them, if they aren't valid, add them to your $_SESSION['errors'] array:
$_SESSION['errors'] = array();
foreach ($fields as $field => $niceName) {
if (empty($_POST[$field])) {
$_SESSION['errors'][$field] = $niceName . ' cannot be empty';
} elseif ($field == 'password' && strlen($_POST[$field]) < 5) {
$_SESSION['errors'][$field] = 'Choose a longer password';
}
}
Then, if $_SESSION['errors'] isn't empty, you can redirect:
if (!empty($_SESSION['errors'])) {
header('Location: register.php');
exit();
}
Related
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 am new to php and I wrote this code:
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ((isset($_POST['username']) == $usernametest ) && (isset($_POST['password']) == $passwordtest ))
{ include ('templates/main.php');
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
I made 2 text boxes and a submit button, I want the user to be directed to another page if the username equals Testing and the password equals TestingPass, and if the user doesnt type in the right combination I want the site to say the username and pass are incorrect. Also, where am I supposed to paste this code exactly? above the text boxes codes ?
You have error in condition checking and redirecting:
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ((isset($_POST['username']) && $_POST['username'] == $usernametest ) && (isset($_POST['password']) && $_POST['password'] == $passwordtest ))
{
header('location: templates/main.php');
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
You want to use header(). You should therefore not have an include in that condition, as headers will already be sent.
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ($_POST['username'] == $usernametest && $_POST['password'] == $passwordtest)
{
header("Location: MY_PAGE.php");
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
Isset() function checks if variable exists and returns boolean. You must check equality like this:
if ($_POST['username'] == $usernametest && $_POST['password'] == $passwordtest)
Always store values in variable to make code more understandable
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == $usernametest && $password == $passwordtest ))
{ header("location:templates/main.php");
}
else
{
echo "please enter the correct username and password combination"; exit();
}
}
?>
I have been using the code below to validate my user input by $_POST:
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
This code checks whether 'name' was actually set, which is obvious and clear and needed.
Secondly, it checks whether user typed something in textfield to give a value for name.
However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.
I found one way of doing it right:
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
if(empty($n)) {
$errors[] = "Please give a name";
}
}
else {
$errors[] = "Please give a name";
}
But here I am repeating same error message twice, so how can it be optimized?
if(isset($_POST['name']) && trim($_POST['name']) !== "") {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Remove the empty, and just do the trim.
To be honest, you don't even need the isset unless you have notices turned on:
if(trim($_POST['name']) !== "") {
If you don't need the trimmed string, you can move the trim itself to the if-clause:
if(isset($_POST['name']) && (trim($_POST['name']) != '') ) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
If you further need it, you could modify the input before checking:
$_POST['name'] = trim( $_POST['name'] );
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Try like this
if(trim(isset($_POST['name']))) {
$n = trim($_POST['name']);
}
else {
$errors[] = "Please give a name";
}
try
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
}
if(empty($n) or !isset($_POST['name'])) {
$errors[] = "Please give a name";
}
Just change your above code to this
if(trim(isset($_POST['name'])))
{
$n = trim($_POST['name']);
}
else
{
$errors[] = "Please give a name";
}
Try using this
if(isset($_POST['name']) && trim($_POST['name']) != false) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Finally I came to use the following code. It is better because here I can even control minimum number of characters.
if(isset($_POST['name']) && strlen(trim($_POST['name'])) > 1) {
$block->name = trim($_POST['name']);
}
else {
$errors[] = "Please give a name. It should be at least two characters";
}
I created a very simple login page where I validate the username and password on PHP after submitting the form.
My first step in the validation is to check that the username and password are not empty, if empty I send the user back to the login page:
$e = $_POST['email'];
$p = $_POST['password'];
if($e == '' || $p == '' || is_null($e) || is_null($p)){
header('Location: login.php?e=missing');
}
it turns out that the if statement that checks if the username and password are empty only works if I add an else statement:
$e = $_POST['email'];
$p = $_POST['password'];
if($e == '' || $p == '' || is_null($e) || is_null($p)){
header('Location: login.php?e=missing');
}else{
//more validation
}
To be honest, my code works, I added the else and problem solved, but WHY???
Thanks.
$e = $_POST['email'];
$p = $_POST['password'];
if(trim($e) == '' || trim($p) == ''){
header('Location: login.php?e=missing');
exit(); // add this else it wont leave the page!
}else{
//more validation
}
if($e == '' || $p == ''){
header('Location: login.php?e=missing');
}
You need to add an exit() after the header line; otherwise, processing continues as normal and all the rest of the code is run.
you need to use empty to check if the variables are set, as well as empty.
$e = $_POST['email'];
$p = $_POST['password'];
if( empty($e) || empty($p) ) {
header('Location: login.php?e=missing');
exit;
}
else {
//more validation
}
$e = $_POST['email'];
$p = $_POST['password'];
if(!empty($e) && !empty($p))
{
header('Location: login.php?e=missing');
exit();
}
else
{
//more validation
}
if($e == '' || $p == ''){
header('Location: login.php?e=missing');
}
rathen then that use :
if(!isset($e) || !isset($p)){
header('Location: login.php?e=missing');
exit();
}
It is happens because of white space or you can use trim() function to remove white space and use exit(); after header its mandatory*
I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...