PHP - if conditional statement skipped unless an else is specified - php

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*

Related

How do I handle and display multiple form validation errors?

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();
}

PHP code not working - if and redirecting to a page

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();
}
}
?>

elseif not working in user specific login

I'm trying to setup a very basic login that will go to one of two pages depending on the "type" of user, either a member, or an officer. I can make it work for the officer, or make it work for the member but when I try to use elseif it doesn't work right. my "officer" user can login, but he gets taken to the member's page. My "member" user can't login at all. Thanks for any help.
Here is my code:
<?php
if (!file_exists($userlist) || !is_readable($userlist)) {
$error = 'There is a major jam up at the Login Center. Please try again later.';
} else {
// read the file into an array called $users
$users = file($userlist);
// loop through the array to process each line
for ($i = 0; $i < count($users); $i++) {
// separate each element and store in a temporary array
$tmp = explode(',', $users[$i]);
// check for a matching record
if ($tmp[0] == $username && $tmp[1] == $password && rtrim($tmp[2]) == 'member') {
$_SESSION['authenticated'] = 'member';
$_SESSION['start'] = time();
session_regenerate_id();}
elseif ($tmp[0] == $username && $tmp[1] == $password && rtrim($tmp[2])== 'officer') {
$_SESSION['authenticated'] = 'officer';
$_SESSION['start'] = time();
session_regenerate_id();
break;
}
}
// if the session variable has been set, redirect
if (isset($_SESSION['authenticated']) || $SESSION['authenticated'] == 'member'){
header("Location: $members_redirect");
exit;}
elseif (isset($_SESSION['authenticated']) || $SESSION['authenticated'] == 'officer'){
header("Location: $officers_redirect");
exit;
} else {
$error = 'Invalid username or password.';
}
}
You have || (or) instead of && (and)
Try this
if (isset($_SESSION['authenticated']) && $SESSION['authenticated'] == 'member'){
header("Location: $members_redirect");
exit;
}
elseif (isset($_SESSION['authenticated']) && $SESSION['authenticated'] == 'officer'){
header("Location: $officers_redirect");
exit;
}
You have a missing underscore in your $_SESSION variable in your if and elseif
if (isset($_SESSION['authenticated']) || $SESSION['authenticated'] == 'member')
change to:
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == 'member')
elseif (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == 'officer')

FILTER_VALIDATE_EMAIL not working

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.

registration form in 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>';
}

Categories