Page 1 of 1

Displaying a list of the errors and re-displaying a form???

Posted: Wed Dec 14, 2011 5:42 pm
by midnite
Hi there guys im doing a simple login system using a flat file, i've managed to do the hardest but for some reason i cant seem to figure it out how to echo the errors as a list below the form also i'm having problems in re-displaying the form so that when a user writes his username and does not write his password he gets a message saying something like 'choose a password' but the username stays in the form...any ideas!!!
here is the code:

common.php

Code: Select all

<?php

session_start();

function registerUser($user,$pass1,$pass2){
	
$errors = '';

$clean_data = array();
	
$file_dir = 'xxxx/xxxxx/xxx.txt';
// Check username 
if(preg_match('/^[a-z\d]{4,20}$/i',$_POST['name']) ) {

	$username = trim($_POST['name']);

} else {

	$errors = 'Username not valid! - minimum 4 characters, no spaces ';	

}		
	
if ($pass1 != $pass2) {
	$errors = "Passwords are not identical!";
} elseif (strlen($pass1) < 6) {
	$errors = "Password is to short!";
}

		

	// Check user existance	
	$handle = fopen($file_dir,"a+");
    rewind($handle);

    while (!feof($handle)) {
        $line = fgets($handle);
        // $usi = user name input ex tmp
        $usi = explode(':', $line);
        if ($usi[0] == $user) {
            $errors = "Username not available choose another!!";
            break;
        }
    }
	
    // If everything is OK -> store user data
    if ($errors == ''){
		// Secure password string
		$userpass = md5($pass1);
    	
		fwrite($handle, "\r\n$user:$userpass");
    }
    
    fclose($handle);
    
	
	
	return $errors;
}



function loginUser($user,$pass){
	$errors = '';
	$validUser = false;
	$file_dir = '/home/pcurad01/private_data/users.txt';
	
	// Check user existance	
	$handle = fopen($file_dir,"r");
    rewind($handle);

    while (!feof($handle)) {
        $line = fgets($handle);
        $usi = explode(':', $line);
        if ($usi[0] == $user) {
            // User exists, check password
            if (trim($usi[1]) == trim(md5($pass))){
            	$validUser= true;
            	$_SESSION['username'] = $user;
            }
            break;
        }
    }
    fclose($handle);

    if ($validUser != true) $errors = "Invalid username or password!";
    
    if ($validUser == true) $_SESSION['validUser'] = true;
    else $_SESSION['validUser'] = false;
	
	return $errors;	
}

function logoutUser(){
	unset($_SESSION['validUser']);
	unset($_SESSION['username']);
}

function checkUser(){
	if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true)){
		header('Location: login.php');
	}
}


?>
register.php

Code: Select all

<?php

	require_once('common.php');

	if (isset($_POST['submit'])){

		// Get user input

		$username  = isset($_POST['name']) ? $_POST['name'] : '';

		$password1 = isset($_POST['password1']) ? $_POST['password1'] : '';

		$password2 = isset($_POST['password2']) ? $_POST['password2'] : '';

        

		// Try to register the user

		$error = registerUser($username,$password1,$password2);

	}	
	require 'form.php';

?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

<html>

<head>

   <title>PHP FMA 2011</title>

</head>

<body>
	<h1>PHP FMA 2011</h1>
	<div id="navbar">
	<ul>
		<li><a href="index.php">Home</a></li>
		<li><a href="about.php">About Us</a></li>
		<li><a href="database.php">Search Our Database</a></li>
	</ul>
	</div>

    <div id="main">
    <?php 
		if ((!isset($_POST['submit'])) || ($error != '')) {
			echo '<h2>Register</h2>';
			echo $output;
		}
	?>

     

	<?php 

 

 	   if (isset($_POST['submit'])){



			if ($error == '') {

				echo " User: $username was registered successfully!<br/><br/>";

				echo ' <a href="login.php">You can login here</a>';

			}

			else {
				echo $error;
			}
		}

	?>

	</div>

</body>   

</html>
and form.php

Code: Select all

<?php
$output = '';

$output .= '<form action="'.htmlentities($_SERVER['PHP_SELF']).'"method="post">



            <fieldset>



                <div>

                    <label for="fn">Username</label>

                    <input type="text" name="name" id="fn" size="40" value="'.(isset($clean['name']) ? htmlentities($clean['name']) : '') .'" />

                </div>



                <div>

                    <label for="em">Choose a Password</label>
                    <input class="text" name="password1" type="password" value="'.(isset($clean['password1']) ? htmlentities($clean['password1']) : '') .'" />
                <div>

                    <label for="em">Re-Enter your Password</label>    
                    <input class="text" name="password2" type="password" value="'.(isset($clean['password2']) ? htmlentities($clean['password2']) : '') .'" />

				</div> 
				<div>

                    <label for="em">Enter your e-mail address</label>                  
                    <input type="text" name="email" id="em" size="40" value="'.(isset($clean['email']) ? htmlentities($clean['email']) : '') .'" />

                </div>



                <input type="submit" name="submit" value="Log In" />

				<input type="submit" name="logout" value="Log Out" />



            </fieldset>

        </form>';
?>
Thank you guys in advance.

Re: Displaying a list of the errors and re-displaying a form

Posted: Wed Dec 14, 2011 11:27 pm
by social_experiment
Make $errors an array and add an error to it each time one occurs; currently a new error will overwrite any existing ones.

To get the error messages to display on the same page as the form you can either use session variables or you can place the the code that checks the form on the same page; in this case form.php. It looks like you are already displaying data that was previously entered in the form page code

Re: Displaying a list of the errors and re-displaying a form

Posted: Thu Dec 15, 2011 4:45 am
by midnite
hi there social_experiment thank you for your reply, right so maybe i did not explain myself the way i should, im already displaying the errors on the same page i just dnt want the user to re-writte his/her name again if the only thing he/her wrote wrong was the email, do you understand what i mean, i know im suppose to do $_SERVER['PHP_SELF'] but for some reason i cant manage to achieve this..any ideas, and thank you for the $errors array it did worked.

Re: Displaying a list of the errors and re-displaying a form

Posted: Thu Dec 15, 2011 5:13 am
by social_experiment
midnite wrote:i just dnt want the user to re-writte his/her name again if the only thing he/her wrote wrong was the email, do you understand what i mean
Yes i understand what you have in mind :) You don't need to use $_SERVER['PHP_SELF'], and it's better if you leave the action attribute blank if you wish to call the form on itself.

To display the value previously entered again you can use isset()

Code: Select all

 // input field
 <input type="text" name="myName" size="20" value="<?php if (isset($_POST['myName'])) echo $_POST['myName']; ?>" />

Re: Displaying a list of the errors and re-displaying a form

Posted: Thu Dec 15, 2011 9:43 am
by midnite
Ooohhhhh you are my very good friend from now on :D , if you could only imagine the hours I've wasted reading about re-displaying forms, $_SERVER['PHP_SELF'], trying all possible scenarios :banghead: ....anyway I've follow your advise and it works like a charm also may i ask why i don't need to use $_SERVER['PHP_SELF'] on the action attribute?? I'm only asking because i did left it on and it still works :D final question in your opinion should i start_session() on the file that checks the user registration, login etc (common.php) or on the file that has the HTML tags the one that is presented to the public, I'm asking this because I'm still a student at uni and my teacher told us to do it always on the file that has the HTML tags in this case the register.php but after looking on http://www.php.net i found out this way as well so i was wondering which is best and why....Once again Thank you so much for your help social_experiment.

Re: Displaying a list of the errors and re-displaying a form

Posted: Thu Dec 15, 2011 10:56 am
by social_experiment
http://blog.codingadventure.com/2010/11 ... rphp_self/
This url explains a bit of the why not in using $_SERVER['PHP_SELF'].
midnite wrote:final question in your opinion should i start_session() on the file that checks the user registration, login etc (common.php) or on the file that has the HTML tags the one that is presented to the public
It depends where you use session variables; imo calling session_start() on a page that doesn't register any session variables is moot; rather place it where it is going to be used but that's just my opinion :)

Have a look at this url http://www.tizag.com/phpT/phpsessions.php