Jump to content
Sign in to follow this  
codeminer

form validation

Recommended Posts

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */


// define variables and set to empty values
$usernameErr = $passwordErr = $firstnameErr = $emailErr = $genderErr = $websiteErr = "";
$username = $password = $firstname = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (empty($_POST["username"])) {
    $usernameErr = "UserName is required";
  } else {
    $username = test_input($_POST["username"]);
    
    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
      $usernameErr = "Only letters and white space allowed"; 
    }
  }
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,}/",$password)) {
      $passwordErr = "<br>Password must be a  mixure of <br>no# and letters containing <br>upper & lower case letters <br>at least 8 charecters<br>long"; 
    }
  }
  
    if (empty($_POST["firstname"])) {
    $firstnameErr = "FirstName is required";
  } else {
    $firstname = test_input($_POST["firstname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
      $firstnameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* Required Fields</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  
  Username:<br/> 
  <input type="text" name="username" value="<?php echo $username;?>">
  <span class="error">* <?php echo $usernameErr;?></span>
  <br><br>
  
  Password:<br/>  
  <input type="password" name="password" value="<?php echo $password;?>
?> ">
  <span class="error">* <?php echo $passwordErr;?></span>
  <br><br>
  
  
  
   Firstname:<br/>  
  <input type="text" name="firstname" value="<?php echo $firstname;?>">
  <span class="error">* <?php echo $firstnameErr;?></span>
  <br><br>
  
  E-mail:<br/>
  <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
 
  Website:<br/>
  <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
 
  Comment:<br/>
  <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
 
  Gender:<br/> 
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type = "reset" name = "reset"/> | 
  <input type="submit" name="submit" value="Submit">  
</form>

<h2><?php echo "WELLCOM!";?> <?php echo  $username;?></h2>

<?php 
$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
 




echo "<br>";
echo $firstname;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;

?>
</body>
</html>

Hello  I need some advise on this   need to make sure this is correct . I took this form from w3shools a long time ago. I modified it with regular expressions went to php.net, pick the hash function manipulated the code a little bit just need to make sure it gonna fly thank you  in advance

Edited by codeminer

Share this post


Link to post
Share on other sites
8 hours ago, codeminer said:

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */


// define variables and set to empty values
$usernameErr = $passwordErr = $firstnameErr = $emailErr = $genderErr = $websiteErr = "";
$username = $password = $firstname = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  
  if (empty($_POST["username"])) {
    $usernameErr = "UserName is required";
  } else {
    $username = test_input($_POST["username"]);
    
    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
      $usernameErr = "Only letters and white space allowed"; 
    }
  }
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{8,}/",$password)) {
      $passwordErr = "<br>Password must be a  mixure of <br>no# and letters containing <br>upper & lower case letters <br>at least 8 charecters<br>long"; 
    }
  }
  
    if (empty($_POST["firstname"])) {
    $firstnameErr = "FirstName is required";
  } else {
    $firstname = test_input($_POST["firstname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
      $firstnameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* Required Fields</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  
  Username:<br/> 
  <input type="text" name="username" value="<?php echo $username;?>">
  <span class="error">* <?php echo $usernameErr;?></span>
  <br><br>
  
  Password:<br/>  
  <input type="password" name="password" value="<?php echo $password;?>
?> ">
  <span class="error">* <?php echo $passwordErr;?></span>
  <br><br>
  
  
  
   Firstname:<br/>  
  <input type="text" name="firstname" value="<?php echo $firstname;?>">
  <span class="error">* <?php echo $firstnameErr;?></span>
  <br><br>
  
  E-mail:<br/>
  <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
 
  Website:<br/>
  <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
 
  Comment:<br/>
  <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
 
  Gender:<br/> 
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type = "reset" name = "reset"/> | 
  <input type="submit" name="submit" value="Submit">  
</form>

<h2><?php echo "WELLCOM!";?> <?php echo  $username;?></h2>

<?php 
//ok i found a article this needs to go in the insert script 
//this is just temporary out put it starting to make more sense
$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
 




echo "<br>";
echo $firstname;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;

?>
</body>
</html>

Hello  I need some advise on this   need to make sure this is correct . I took this form from w3shools a long time ago. I modified it with regular expressions went to php.net, pick the hash function manipulated the code a little bit just need to make sure it gonna fly thank you  in advance

 

Share this post


Link to post
Share on other sites

sorry about this duplication im just not familiar with this editor I can't seem to locate the delete button

Share this post


Link to post
Share on other sites

Don't bother passing a salt to password_hash, let it generate one.  You're also not hashing the password they entered.

Other than that, I don't see the point of using htmlspecialchars in that test_input function, other than that the only thing you do with the form data is print it on the page.  If you're going to store it in a database you don't need to do that.  I also don't like the name of test_input, because it doesn't test anything.  The regular expression to validate the password is also a little bit overboard.  If you want to verify that it contains at least one uppercase letter, one lowercase, one digit, and is at least 8 characters total that's fine, you don't need a big regular expression to do that.  I hate it when some website rejects my complex password because it doesn't fit their arbitrary rules.

Share this post


Link to post
Share on other sites

I read your article that you put up a while back on form page mode very helpful and in depth in fact if I would have discovered sooner I wouldn't have post this

I know im just printing the hash out on the page .I Relies that it needs to be defined in the insert statement .what im trying to learn is how to put it  in the insert statement so that hashing of the password is accomplished in db . as far as the specialchars i never used them before i 'm trying to learn security  . here is my insert  file

<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
//____________________________________________	
	//trying to understand how to put this in the statement

	
	}else{

$options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$password = password_hash( "password"
,PASSWORD_BCRYPT, $options);

//_______________________________________					
$sql = "INSERT INTO users (username, password,email,website,comment,gender)
VALUES 
('$_POST[username]', 
 '$_POST[password]',
 '$_POST[email]',
 '$_POST[website]',
 '$_POST[comment]',
 '$_POST[gender]')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully, <a href = 'http://127.0.0.1/A'>Click here to continue</a>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();

 

Share this post


Link to post
Share on other sites

You hash the password prior to inserting in the database, but you add it to the database like any other value.  You wouldn't insert the plain text password from $_POST, you hash that password, get the hashed value, and then insert that hashed value into the database.  I would recommend that you learn how to use PDO for the database work though.  You need to use prepared statements when you're putting data in a query, and PDO is just easier and less complex for prepared statements than mysqli. 

http://php.net/manual/en/pdo.prepare.php 

http://php.net/manual/en/pdostatement.execute.php

 

Share this post


Link to post
Share on other sites

thank you for your expert advise. I managed to convert the password into the options array prior to inserting in to db using this code. It works!!!YA.THANK YOU

 //password
  
   if (empty($_POST["password"])) {
    $passwordErr = "password word is required";
  } else {
    $password = test_input($_POST["password"]);
   //changed the regular expression you can add up to 60 charecters
    if (!preg_match("/^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{0,60}/",$password)) {
      $password_Err = "<br><P>Password must be a  mixure of no# and letters containing upper & lower case charecters</P>"; 
    }
  }
  
  // changed the name of password  to password_hash call the $options array  this is coverting the  password prior to getting to db it works
  
  
  $options = [
    'cost' => 9,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];

   $password = password_hash($password, PASSWORD_BCRYPT, array( '$options' ));
  

 

Edited by codeminer

Share this post


Link to post
Share on other sites

I thought this worked ,it doesn/'t hash the pass, It puts the hash in the data base  but it fires prematurely it causes the input field to be fill  before the user input is served . just need to keep pounding .hopefully ill get a break through, trial an error unfortunately mostly error

Share this post


Link to post
Share on other sites

ok change the whole file around ,found better  idea .This hashes the password  ,check the db if the username  is available, checks that the im format is true and checks the firstname against RE rules .returns error messages in the browser, i learned this from a video on youtube  


<?php
//This is the insert.php file

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


	
	include_once 'db.php';

	$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
	$email = mysqli_real_escape_string($conn, $_POST['email']);
	$username = mysqli_real_escape_string($conn, $_POST['username']);
	$password = mysqli_real_escape_string($conn, $_POST['password']);
	

	//Error handlers
	//Check for empty fields
	if (empty($firstname) || empty($email) || empty($username) || empty($password)) {
		header("Location: ./index.php?Register=empty");
		exit();
	} else {
		//Check if input characters are valid
		if (!preg_match("/^[a-zA-Z]*$/", $firstname)) {
			header("Location: ./index.php?Register=NameInvalid");
			exit();
		} else {
			//Check if email is valid
			if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				header("Location: ./index.php?Register=Invalid Email");
				exit();
				
			// Checks if username isnt being used by someone else	
			} else {
				$sql = "SELECT * FROM users WHERE username='$username'";
				$result = mysqli_query($conn, $sql);
				$resultCheck = mysqli_num_rows($result);

				if ($resultCheck > 0) {
					header("Location: ./index.php?Resiter=usertaken");
					exit();
				} else {
					//Hashing the password
					$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
					//Insert the user into the database
					$sql = "INSERT INTO users (firstname,email, 
	                username,password) VALUES ('$firstname','$email', '$username', '$hashedPassword');";
					mysqli_query($conn, $sql);
					header("Location: ./index.php?Register=success");
					exit();
				}
			}
		}
	}

} else {
	header("Location: ./index.php");
	exit();
}

 

Share this post


Link to post
Share on other sites

Again, I'd strongly recommend looking into prepared statements.  There's no reason to learn the wrong way to do something, then have to unlearn that and learn the right way.  Just start with the right way.  That means using prepared statements any time a query has data in it (or, for good practice, just every time).  Like I said, mysqli supports prepared statements, but they're easier with PDO.

Share this post


Link to post
Share on other sites

I agree my problem is that I started with mysqli I can due basic function like connect select insert I wanted to try to finish what I started once I get a grip on some of these basics I might have enough understanding to take the plunge with pdo I appreciate your input

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×