Jump to content

Recommended Posts

Hey all,

 

i want to be more secure on my web application, i have a register form with the following fields;

 

firstname

lastname

username

email

password

confirmpassword

 

and here is my register-exec.php script;

 

<?php
//Start session
session_start();

//Include database connection details
require_once('Includes/config.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
	die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
	die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
	$str = @trim($str);
	if(get_magic_quotes_gpc()) {
		$str = stripslashes($str);
	}
	return mysql_real_escape_string($str);
}

//Sanitize the POST values
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);
$login = clean($_POST['login']);
$email = clean($_POST['email']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);

//Input Validations
if($fname == '') {
	$errmsg_arr[] = 'First name missing, ';
	$errflag = true;
}
if($lname == '') {
	$errmsg_arr[] = 'Last name missing, ';
	$errflag = true;
}
if($login == '') {
	$errmsg_arr[] = 'Login ID missing, ';
	$errflag = true;
}
if($email == '') {
	$errmsg_arr[] = 'Email Address is missing, ';
	$errflag = true;
}
if($password == '') {
	$errmsg_arr[] = 'Password missing, ';
	$errflag = true;
}
if($cpassword == '') {
	$errmsg_arr[] = 'Confirmation password missing, ';
	$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
	$errmsg_arr[] = 'Passwords do not match!!';
	$errflag = true;
}

//Check for duplicate login ID
if($login != '') {
	$qry = "SELECT * FROM members WHERE login='$login'";
	$result = mysql_query($qry);
	if($result) {
		if(mysql_num_rows($result) > 0) {
			$errmsg_arr[] = 'Login ID is already in use!<br />';
			$errflag = true;
		}
		@mysql_free_result($result);
	}
	else {
		die("Query failed");
	}
}

	//Check for duplicate email
if($email != '') {
	$qry = "SELECT * FROM members WHERE email='$email'";
	$result = mysql_query($qry);
	if($result) {
		if(mysql_num_rows($result) > 0) {
			$errmsg_arr[] = 'E-Mail address is already in use!';
			$errflag = true;
		}
		@mysql_free_result($result);
	}
	else {
		die("Query failed");
	}
}

//If there are input validations, redirect back to the registration form
if($errflag) {
	$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
	session_write_close();
	header("location: signup.php");
	exit();
}

//Create INSERT query
$qry = "INSERT INTO members(firstname, lastname, login, email, passwd, settings, avatar, membership, roles) VALUES('$fname','$lname','$login','$email','".md5($_POST['password'])."','test1;test9;test2;test10;test3;test11;test4;test12;test5;test13;test6;test14;test7;test8','avatar011','Free','Member')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
	header("location: register-success.php");
	exit();
}else {
	die("Query failed");
}
?>

 

here is my form page;

 

<? require_once('header.php');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
    <head>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="content-style-type" content="text/css" />
        <meta http-equiv="content-script-type" content="text/javascript" />
    <title>Registration</title>

<style>
.style2 {color: #EC1A3F}
.style5 {color: #999999; font-style: italic; }
</style>
</head>

<body>

                            <?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
	echo '<div class="notification error png_bg"><a href="#" class="close"><img src="img/cross_grey_small.png" title="Close this notification" alt="close" /></a><div>';
	foreach($_SESSION['ERRMSG_ARR'] as $msg) {
		echo $msg;
	}
	echo '</div></div>';
	unset($_SESSION['ERRMSG_ARR']);
}
?>
<div>
<div>
  <div>
<div>
				<div class="block">
					<form name="loginForm" method="post" action="register-exec.php">
                            <table border="0" align="center" cellpadding="4" cellspacing="0">
                              <tr>
                                <td>
                                <label><img src="img/icons/name.png" alt="" width="16" height="16" /> First Name:</label>
                                <br />
                                <input class="text" name="fname" type="text" /> 
                                <span class="style2">*<br />
                                </span></td>
                              </tr>
                              <tr>
                                <td>
                                <label><img src="img/icons/name2.png" alt="" width="16" height="16" /> Last Name:</label>
                                <br />
                                <input class="text" name="lname" type="text" /> 
                                <span class="style2">*</span></td>
                              </tr>
                              <tr>
                                <td>
                                <label><img src="img/icons/username.png" alt="" width="16" height="16" /> Username:</label>
                                <br />
                                <input class="text" name="login" type="text" /> 
                                <span class="style2">*<span class="style5"> Used to login to the site</span><br />
                                </span></td>
                              </tr>                               
                              <tr>
                                <td>
                                <label><img src="img/icons/email.png" alt="" width="16" height="16" /> E-Mail Address:</label>
                                <br />
                                <input class="text" name="email" type="text" /> 
                                <span class="style2">* </span><span class="style5">Address is needed to confirm forgotten passwords!</span></td>
                              </tr>
                              <tr>
                                <td>
                                <label><img src="img/icons/key.png" alt="" width="16" height="16" /> Password:</label>
                                <br />
                                <input class="text" name="password" type="password" />
                                  <span class="style2">* </span><span class="style5">Must be more than 6 characters long.</span> </td>
                              </tr>
                              <tr>
                                <td>
                                <label><img src="img/icons/key.png" alt="" width="16" height="16" /> Confirm Password:</label>
                                <br />
                                <input class="text" name="cpassword" type="password" />
                                <span class="style2">*</span></td>
                              </tr>
                              <tr>
                              <td align="left"><br />
                                <input class="Button" type="submit" name="submit" value="Register Me!" /></td>
                              </tr>
                            </table>
				  </form>
</div></div></div></div></div>
</body>

 

it has some validation but not a great deal, how can i change this to stop users entering information such as: "'where%201=1" etc....

 

any help and code would be much appreciated;

 

 

Link to comment
https://forums.phpfreaks.com/topic/198114-form-validation-help/
Share on other sites

You use preg_match or similar function. preg_match will suffice for any sanitization, eg:

 

preg_match("/\A[a-zA-Z_0-9]{1,12}^/",$username);

// This would only return true if; $username contained between 1 and 12 charactrers consisting of any combination of a-z (any case), 0-9 and underscores _.

 

preg_match is an extremely powerful pattern matching function, and i would suggest you ask any "REGEX" (that pattern code) questions in the REGEX forum.

 

-CB-

You use preg_match or similar function. preg_match will suffice for any sanitization, eg:

 

preg_match("/\A[a-zA-Z_0-9]{1,12}^/",$username);

// This would only return true if; $username contained between 1 and 12 charactrers consisting of any combination of a-z (any case), 0-9 and underscores _.

 

preg_match is an extremely powerful pattern matching function, and i would suggest you ask any "REGEX" (that pattern code) questions in the REGEX forum.

 

-CB-

 

sounds interesting,

 

i tried to use your example and modified it for $login,

 

if(preg_match("/\A[a-zA-Z_0-9]{1,12}^/",$login)) {
    	$errmsg_arr[] = 'Username cannot contain illegal characters please us a-Z, 1-9 and underscores ONLY!, ';
	$errflag = true;
} 

 

this wont work and i am able to add other characters in the $login box, can u see why its doing it?

still having problems,

 

no matter what i type in username it still produces the error;

 

//Check for strange characters in username & names
if (!preg_match('/[^a-zA-Z0-9\_\-\]+$/', $login));
{
    	$errmsg_arr[] = 'Username has illegal chacters you can only use; Aa-Zz, 1-9 and _';
	$errflag = true;
}

 

i want to allow a-z, A-Z, 0-9, -, and _

 

am i doing something wrong?

now it doesnt throw up error at all??

 

if(preg_match("/^[a-zA-Z_0-9-.]$/", $login)) { //Check for strange characters in username & names
        $errmsg_arr[] = 'Username has illegal chacters you can only use; Aa-Zz, 1-9 and _';
        $errflag = true;
    }

 

and it lets me put other characters in the signup form such as where=?ID=0'

You keep changing it. Put the "!" back in front of preg_match. You also need to add a "+" before the "$" in the regex. Lastly, replace the "." in the regexp with "\." and move it after "0-9".

 

It should be:

<?php
if (!preg_match("/^[a-z\d_\.-]+$/i", $login)) { ...

 

\d = digits (same as 0-9)

/i = ignore case

Ye sorry bot the typos, the regexp shuu of been:

 

preg_match("/\A[a-z_0-9-]+$/i",$username);

This matches any character u wanted, but with no limit on the amount of characters, but must have a least one of them.

 

For emails i usually go for something that will allow a segmented prefix and suffix (abc.edf.g_hij@some.random.sudomain.co.uk),

something like:

 

"/^[a-z_0-9\.]+@[a-z0-9\.]+\.[a-z]{2,3}$/i"

 

to check your regexp easy just google regexp checker.

 

-CB-

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.