Jump to content

[SOLVED] Form Validation easy one


emediastudios

Recommended Posts

I got this code that checks for empty fields.

#Check for blanks and clean data
if(empty($_POST['username'])) $errors_login[] = 'Please put in your username.'; else $clean['username'] = htmlspecialchars($_POST['username']);
if(empty($_POST['password'])) $errors_login[] = 'Please put in your password.'; else $clean['password'] = htmlspecialchars($_POST['password']);

 

What i want is to add an error if the username or password is incorrect

Anyone, please, its the last bit of code i need.

Link to comment
Share on other sites

In your previous post, your script connects to the database, then checks if username and password are present ($count == 1).

 

You need to place the error check before that

$count=mysql_num_rows($result);
     
        if($_POST['username'] == $count['username']) {
          set session;}
            else {
               echo 'incorret username';
            }

Link to comment
Share on other sites

I gave it a go but i get errors.

Still leatning php, but am getting better with the help from this site.

 

Dont mean to be a pain but how would i implement that code in my code below.

I want the error to be displayed like the other validation, the blank fields validation.

I have a script on my page that displays the errors wher i want them to be displayed.

 

This is my code

<?php

include('includes/include.php');
include('form_email_config.php');

#Form has been submitted?
if((isset($_POST['login'])) AND ($_POST['login'] == 'Login')){
ob_start();
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="5050888202"; // Mysql password 
$db_name="sde"; // Database name 
$tbl_name="salon"; // Table name 

$errors_login = array(); #Initiate error variable
#Check for blanks and clean data
if(empty($_POST['username'])) $errors_login[] = 'Please put in your username.'; else $clean['username'] = htmlspecialchars($_POST['username']);
if(empty($_POST['password'])) $errors_login[] = 'Please put in your password.'; else $clean['password'] = htmlspecialchars($_POST['password']);



// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $username and $password 
$username=$_POST['username']; 
$password=$_POST['password']; 

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row

if($count==1){
// Register $username, $password and redirect to file "templates.php"
session_register("username");
session_register("password"); 
header("location:templates.php");
}
else {

ob_end_flush();
}
}
?>

 

This my error reporting script.

 

<?php
	if(!empty($errors_login)){
		echo "<p><span class='red'>";
		foreach($errors_login as $error_login){
			echo $error_login."<br />";
		}
		echo "</span></p>";
	}
	?>

Link to comment
Share on other sites

also, these 2 statements

 

if(empty($_POST['username'])) $errors_login[] = 'Please put in your username.'; else $clean['username'] = htmlspecialchars($_POST['username']);

if(empty($_POST['password'])) $errors_login[] = 'Please put in your password.'; else $clean['password'] = htmlspecialchars($_POST['password']);

 

 

dont have any {} in them, I also am new to php, but I dont think they are optional

Link to comment
Share on other sites

ok, i made some changes and got it to work.

 

Added this code

//verify user...
$get_user = mysql_query("SELECT * FROM `salon` WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."'");
$q = mysql_fetch_object($get_user);
   if(!$q) die("Login Failure: An error occured, please verify your username and password are correct.");

 

But i dont want the error to echo on a blank page.

I want it to echo like the other validation script.

 

Any ideas?

 

 

Link to comment
Share on other sites

also, these 2 statements

 

if(empty($_POST['username'])) $errors_login[] = 'Please put in your username.'; else $clean['username'] = htmlspecialchars($_POST['username']);

if(empty($_POST['password'])) $errors_login[] = 'Please put in your password.'; else $clean['password'] = htmlspecialchars($_POST['password']);

 

 

dont have any {} in them, I also am new to php, but I dont think they are optional

I got this script off the net, it works so i will leave it, thanks anyway. ;)

Link to comment
Share on other sites

ok, please someone.

This is what i need.

 

This script

//verify user...
$get_user = mysql_query("SELECT * FROM `salon` WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."'");
$q = mysql_fetch_object($get_user);
    if(!$q) die("Login Failure: An error occured, please verify your username and password are correct.");

 

But i dont want this section,

if(!$q) die("Login Failure: An error occured, please verify your username and password are correct.");

 

I want something like this

if (!$q)  $errors_login[] = 'Wrong username or password.'; else $clean['password'] = htmlspecialchars($_POST['password']);

 

I have tried but cant get it to work

???

Link to comment
Share on other sites

But i dont want the error to echo on a blank page.

I want it to echo like the other validation script.

 

Any ideas?

 

 

 

sounds to me like...

 

since you redirect to templates.php, if there is a error it will try to redirect but fail, so it displays errors but doent redisplay the form or display templates, am i right to assume, templates is the page past your login where users can alter content?

 

i would recomend that you make sure your submit button is posting to $_SERVER['PHP_SELF'], that should redisplay the login forms if there is an error

 

i am also including my login script so you can see where i am going with this

 

note: it is NOT secure

note 2: i use pear db, so some things would need to be changed

note 3: formhelpers.php is a nifty set of functions that make forms really easy

 

<?php
session_start();
require ('../../install/PEAR/DB.php');
require ('../../../dbfiles/db_login.php');
require ('../../cgi-bin/formhelpers.php');
$db->setErrorHandling(PEAR_ERROR_DIE);
$db->setFetchMode(DB_FETCHMODE_ASSOC);

if($_POST['_submit_check']){
if($form_errors = validate_form()){
	show_form($form_errors);
} else {
	process_form();
}
} else {
show_form();
}

function show_form($errors = '') {

if ($errors){
	print 'Please correct these errors: <ul><li>';
	print implode('</li><li>', $errors);
	print '</li></ul>';
}

print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
//begin the unique form

print 'Username:';
input_text('username', $_POST);
print '<br />';

print 'Password:';
input_password('password', $_POST);
print '<br />';

input_submit('submit', 'Log In');

print '<input type="hidden" name="_submit_check" value="1" />';
print '</form>';
}

function validate_form(){
global $db;

//check that username is entered
if (trim(strlen($_POST['username'])) == 0) {
	$errors[]= "You must enter a username.";
}

//check that username is only letters or numbers
if (! preg_match('/^[a-zA-Z0-9]+$/i', $_POST['username'])){
	$errors[]= "Your username must be <i><b>ONLY</b></i> letters or numbers.";
}

//check that the username exists
$q = $db->query("SELECT username FROM users WHERE username = '$_POST[username]'");
if ($q->numrows() == 0 ){
	$errors[] = 'Please enter a valid username.';
}


//check that password is entered
if (trim(strlen($_POST['password'])) == 0) {
	$errors[]= "You must enter a password.";
}

//check that password is only letters or numbers
if (! preg_match('/^[a-zA-Z0-9]+$/i', $_POST['password'])){
	$errors[]= "Your password must be <i><b>ONLY</b></i> letters or numbers.";
}

//check that password matches username
$encrypted_password = $db->getOne("SELECT password FROM users WHERE username = '$_POST[username]'");
if ($encrypted_password != crypt($_POST['password'], $encrypted_password)){
	$errors[] = 'Please enter a valid password.';
}
//$errors[]=$encrypted_password;

return $errors;

}

function process_form(){
$username = $_POST['username'];


//add username to session
$_SESSION['username'] = $username;

print "Welcome, {$_SESSION['username']}";

//instead of having this link below, just make an include to template.php, template will be displayed upon successul login
print '<a href="/0/admin/managearticle/index.php">Continue here</a>';
}

?>

 

i put a note near the bottom for you

Link to comment
Share on other sites

Thanks so much.

I have spent hours on this, but hey, i quess thats how you learn.

I altered the code to this

	//verify user...
$get_user = mysql_query("SELECT * FROM `salon` WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."'");
$q = mysql_fetch_object($get_user);
    if(!$q) { 
$errors_login[] = 'Wrong username or password.'; 
}

 

and it all works just dandy now.

I will improve on my script by studying your script and altering mine at a later date.

One again, thanks everyone for the help.

;D

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.