Am new to php and am taking a web application development to allow come across different skill, problems and find a way to fix them.
Am now creating a registration form and validating the form and protecting it against SQL Injection and XSS. NOTE I understand could have use prepared statement, but for my level of skill i think starting from Mysqli procedural wold be best result for my development until if fill confident enough.
So i just want you the expert to see if there is something i needed to remove or add or use instead (apart from stmt).
Here is my Register page.
<?php
// define mqsqli real escape string function
function _olaskee($escape) {
$escape = htmlspecialchars ($escape, ENT_QUOTES, 'UTF-8');
$escape = trim ($escape, ENT_QUOTES, 'UTF-8');
$escape = stripcslashes ($escape, ENT_QUOTES, 'UTF-8');
return $escape;
}
// start session
session_start();
// include database connection
//require_once('include/connection.php');
// if user type already detected, redirect to index.php
if(isset($_SESSION['user_type'])){
header('Location: index.php');
}
// check if we have submited / if the for as being submitted
if(!empty($_POST['submit'])){
//instantiate
$firstname = _olaskee($con, $_POST['firstname']);
$lastname = _olaskee($con, $_POST['lastname']);
$user_name = _olaskee($con, $_POST['user_name']);
$user_type = _olaskee($con, $_POST['user_type']);
$password = _olaskee($con, $_POST['password']);
$confirm_password = _olaskee($con, $_POST['confirm_password']);
// hash password
$hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
// include database connection
require_once('include/errMsg.php');
}
// include page title
$title = 'Registration Page';
// include header layout
require_once('include/header.php');
?>
<div>
<form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value='<?php// echo htmlspecialchars ($firstname) ?>'><br><span style='color: red'><?php echo $fnErr ?></span></td>
<?php echo $firstname ; ?>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value='<?php echo htmlspecialchars ($lastname) ?>'><br><span style='color: red'><?php echo $lnErr ?></span></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user_name" value='<?php echo htmlspecialchars ($user_name) ?>'><br><span style='color: red'><?php echo $unameErr ?></span></td>
</tr>
<tr>
<td>User Type</td>
<td>
<!-- <label for="flavor">Select User Type:</label > -->
<select id="user_type" name='user_type' >
<option value="">Select User Type</option>
<option <?php echo $user_type=='rsw'?'selected':''; ?> >rsw</option>
<option <?php echo $user_type=='sp'?'selected':''; ?> >sp</option>
</select>
<span style='color: red'><?php echo $u_typeErr?></span>
</td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" value='<?php echo htmlspecialchars ($email) ?>'><br /><span style='color: red'><?php echo $emailErr ?></span></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password"><br /><span style='color: red'><?php echo $passErr ?></span></td></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password" id="confirm_password"><br /><span style='color: red'><?php echo $cpassErr ?></span></td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Register"><a href='index.php'> Login</a></td>
</tr>
</table>
</form>
</div>
<?php
if(is_file('include/footer.php'))
include_once('include/footer.php');
?>
And here is my error message page
<?php
// error handler variable
$fnErr = $lnErr = $unameErr = $u_typeErr = $emailErr = $passErr = $cpassErr = '';
$firstname = $lastname = $user_name = $user_type = $email = $password = $confirm_password = '';
// if submit, then validate
$firstname = ($_POST['firstname']);
// set field validation for first name
if (empty($firstname)){
$fnErr = 'Field empty, please enter your first name';
}else{
if (strlen($firstname) < 3){
$fnErr = 'First Name is too short';
}
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$fnErr = "Only letters and white space allowed";
}
// set field validation for last name
$lastname = ($_POST['lastname']);
if (empty($lastname)){
$lnErr = 'Field empty, please enter your last name';
}else{
if (strlen($lastname) < 3){
$lnErr = 'Last Name is too short';
}
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lnErr = "Only letters and white space allowed";
}
// set field validation for user name
$user_name = ($_POST['user_name']);
if (empty($user_name)){
$unameErr = 'Field empty, please enter user name';
}else{
if (strlen($user_name) < 6){
$unameErr = 'Password is too short';
}else{
if (strlen($user_name) > 15){
$unameErr = 'Password is too long';
}
}
}
// check if name only contains letters and whitespace
if (!preg_match("#.*^(?=.*[a-z])(?=.*[A-Z]).*$#",$user_name)) {
$unameErr = "At least one CAPS, letters and white space allow";
}
// check if user select user type from list
$user_type = ($_POST['user_type']);
if (empty($user_type)){
$u_typeErr = 'Please select user type from list';
}
// set email filter validation
$email = ($_POST['email']);
if (empty($email)){
$emailErr = 'Field empty, please enter your last name';
}else{
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// set field validation for password
$password = ($_POST['password']);
if (empty($password)){
$passErr = 'Field empty, please create a password';
}else{
if (strlen($password) < 6){
$passErr = 'Password is too short';
}else{
if (strlen($password) > 15){
$passErr = 'Password is too long';
}
}
}
if( !preg_match("#[A-Z]+#", $password) ) {
$passErr = "Password must include at least one CAPS! ";
}else{
if( !preg_match("#[0-9]+#", $password) ) {
$passErr = "Password must include at least one NUMBER! ";
}
}
// // // check if name only contains letters and whitespace
// if (preg_match("#.*^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $password)) {
// $passErr = "Try again... Password must contain NUMBER, LETTER and CAPS";
// }
// set field validation for confirm password
$confirm_password = ($_POST['confirm_password']);
if (empty($confirm_password)){
$cpassErr = 'Field empty, please confirm your password';
}else{
if ($password != $confirm_password) {
$cpassErr = 'Error... Passwords do not match';
}
}
// // define mqsqli real escape string function
// function _olaskee($escape) {
// $escape = htmlspecialchars ($escape, ENT_QUOTES, 'UTF-8');
// $escape = trim ($escape, ENT_QUOTES, 'UTF-8');
// $escape = stripcslashes ($escape, ENT_QUOTES, 'UTF-8');
// return $escape;
// }
?>
NOTE have commented out some lines in both pages.
Also in the register page have include the security function at the top of the session unsure if that's right.
Also have used the password hashing, but i haven't test in on database yet, but (have i used it right?)
Please just have a look and give me your expert opinion
Best Regards
I am not an expert but I can give you some notes. In your sanitizing function _olaskee, I think you need to understand what these functions does and how to use it
You don't need stripcslashes here. This function removes the slashes why are you putting it here?
You don't need to sanitize the password. You will be hashing it before using it and hashing will replace any injected code
For sanitizing against SQL Injection you need to use mysqli_real_escape_string It will take care of sanitizing strings.
Take a look at filter_var function. You will find it very useful in sanitizing and validating your inputs. This function allows you to validate against a specified length, allow some HTML tags in certain inputs (like textarea) and so on
To understand how to protect yourself from attacks you need to know first how the attacks are made. Read about SQL Injections and see if you can hack your database through vulnerable code.
You may try also try ZAP tool. You can use automatic scan by just passing the URL of your site and it will automatically scan your web app and report any vulnerabilities it finds
It is good to learn how to make a login system. But for real world applications, it is not advised to make your own login system. Always rely on tested and approved software or you will be creating systems full of vulnerabilities. Good luck!
Related
This question already has an answer here:
Check to see if an email is already in the database using prepared statements
(1 answer)
Closed 6 years ago.
I am trying to check if username already exits in DB. have already done this easily with mysqli, but am trying to secure all my database query by using Prepared Statement.
Below is the code for both Mysqli and prepared statement.
<?php
ini_set('display_errors', 0);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// start session
session_start();
// include connection
require_once('include/connection.php');
// if user is loggin, redirected to homepage
if(isset($_SESSION['user_type'])){
header('Location: index.php');
}
$error[] = "";
if(isset($_POST['submit'])) {
$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$user_type = $_POST['user_type'];
$user_name = trim($_POST['user_name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
// $password = mysqli_real_escape_string($con, trim($_POST['password'], ENT_QUOTES, 'UTF-8'));
// $confirm_password = mysqli_real_escape_string($con, trim($_POST['confirm_password'], ENT_QUOTES, 'UTF-8'));
// password hash security
$hash_pass = password_hash($password, PASSWORD_BCRYPT);
extract($_POST);
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter your first name';
}else{
if (strlen($firstname) < 3){
$error[] = 'First Name is too short';
}
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$error[] = "Only letters and white space allowed";
}
if (empty($lastname)){
$error[] = 'Field empty, please enter your last name';
}else{
if (strlen($lastname) < 3){
$error[] = 'Last Name is too short';
}
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$error[] = "Only letters and white space allowed";
}
if (empty($user_name)){
$error[] = 'Field empty, please enter your username';
}else{
if (strlen($user_name) < 3){
$error[] = 'UserName is too short';
}
}
//if( $query = "select * from user where user_name = "."'".trim($user_name)."'" );
// $result = mysqli_query($con,$query);
// if(mysqli_num_rows($result)){
// $error[] = "User Name Already Exist, try other";
// header('Location: '.$_SERVER['PHP_SELF']);
// }
/* create a prepared statement */
if($stmt = mysqli_prepare($con, "SELECT user_name FROM user WHERE user_name = ?"));
// $stmt = mysqli_query($con, $query);
/* bind param variables */
mysqli_stmt_bind_param($stmt, 's', $user_name);
/* execute statement */
mysqli_stmt_execute($stmt);
/* store result */
// mysqli_stmt_store_result($stmt);
/* num rows */
if(mysqli_stmt_num_rows($stmt) > 0) {
$error[] = "User Name Already Exist, try other";
header('Location: '.$_SERVER['PHP_SELF']);
}
//}
// validate user type option
if (empty($user_type)){
$error[] = 'Please select user type from list';
}
// set email filter validation
if (empty($email)){
$error[] = 'Field empty, please enter your email address';
}else {
$query = "select * from user where email = "."'".trim($email)."'";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result) == 1){
$error[] = "Chosen email Already Exist, please choose another ";
// header('Location: '.$_SERVER['PHP_SELF']);
}
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format";
}
}
if (empty($password)){
$error[] = 'Field empty, please create a password';
}else{
if (strlen($password) < 6){
$error[] = 'Password is too short';
}
if (strlen($password) > 15){
$error[] = 'Password is too long';
}
if ( !preg_match("#[A-Z]+#", $password) ) {
$error[] = "Password must include at least one CAPS! ";
}else{
if( !preg_match("#[0-9]+#", $password) ) {
$error[] = "Password must include at least one NUMBER! ";
}
}
}
// set field validation for confirm password
if (empty($confirm_password)){
$error[] = 'Field empty, please confirm your password';
}else{
if ($password != $confirm_password) {
$error[] = 'Error... Passwords do not match';
}
}
//if no errors have been created carry on
if(!isset($error)){
$created_at = date('Y-m-d');
$queryInsert = "insert into user
(firstname,lastname,user_name,
user_type,email,password,
created_at)
values ('$firstname','$lastname','$user_name',
'$user_type','$email','$hash_pass',
'$created_at')";
$resInsert = mysqli_query($con,$queryInsert);
if($resInsert){
$_SESSION['main_notice'] = "Successfully registered, login here!";
header('Location: index.php');
exit;
}else{
$_SESSION['main_notice'] = "Some error, try again";
header('Location: '.$_SERVER['PHP_SELF']);
}
}
//}
}
// exit mysqli connection
// title page
$title = "Registration Page";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_SESSION['main_notice'])) {
?>
<div class="main-notice">
<p>
<?php
echo $_SESSION['main_notice'];
//unset($_SESSION['main_notice']);
?>
</p>
</div>
<?php
}
?>
<div>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p style="color: red">'.$error.'</p>';
}
}
?>
<form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value='<?php if(isset($error)){ echo $_POST['firstname']; } ?>'</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value='<?php if(isset($error)){ echo $_POST['lastname']; } ?>'</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user_name" value='<?php if(isset($error)){ echo $_POST['user_name']; } ?>'></td>
</tr>
<tr>
<td>User Type</td>
<td>
<select name="user_type" required>
<option selected>Please choose user type</option>
<option value="member">RSW</option>
<option value="admin">Admin</option>
<option value="leader">SP</option>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" value='<?php if(isset($error)){ echo $_POST['email']; } ?>'</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" value='<?php if(isset($error)) ?>'></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password" id="confirm_password" value='<?php if(isset($error)) ?>'></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
<tr>
<td></td>
<td>Login</td>
</tr>
</table>
</form>
</div>
<?php
if(is_file('include/footer.php'))
include_once('include/footer.php');
?>
Have comment out the mysqli. Am not receiving error but the form is not executing.
Note have also comment out the mysqli_stmt_store_result because I don't see what that does really.
You have used prepared statement and why for you combine the mysqli.* along with all the queries that you execute. You can better change the queries as per the normal prepared statement process.
You can use the num_rows so that it will help you to fetch the count of the queries executed above.
Replace your Prepared Statement like this:
<?php
$stmt = mysqli_prepare($con, "SELECT user_name FROM user WHERE user_name = ?");
$stmt -> bind_param("s", $user_name);// Here you will bind the parameters
$stmt -> execute(); // here it will execute the statement
$numberofrows = $stmt->num_rows; // here if will fetch the count
if($numberofrows > 0) {
$error[] = "User Name Already Exist, try other";
header('Location: '.$_SERVER['PHP_SELF']);
}
else
{
// This part is for user name mot present.
}
?>
The Mysqli way you can have like this.
<?php
$stmt = mysqli_prepare($con, "SELECT user_name FROM user WHERE user_name = '".$user_name."'");
$stmt->execute(); // here it will execute the statement
$numberofrows = $stmt->num_rows; // here if will fetch the count
if($numberofrows > 0) {
$error[] = "User Name Already Exist, try other";
header('Location: '.$_SERVER['PHP_SELF']);
}
else
{
// if the user name is not present
}
?>
I really need a help. I know there are similar help with my, but have tried them out no luck.
Am creating a Registration system with user type using PHP and Mysqli procedural. Am just starting up with PHP so please bear with me.
I need help with form validation... it looks OK to me, but the error is not processing. Below is my register and errMsg code.
Connection Code:
define('HOST','localhost');
define('USERNAME','');
define('PASSWORD','');
define('DBNAME','');
$con=mysqli_connect(HOST,USERNAME,PASSWORD,DBNAME)or die('ERROR WHILE CONNECTING TO DATABASE SERVER');
?>
Registration and errMsg code
<?php
session_start();
if(is_file('include/connection.php'))
include_once('include/connection.php');
else
exit('Database FILES MISSING:(');
?>
<?php $_SESSION['main_title'] = "Registration Page"; ?>
<?php
if(isset($_SESSION['user_type'])){
header('Location: index.php');
}
if(isset($_POST['submit']))
{
extract($_POST);
// $name = $_POST["name"];
// $email = $_POST["email"];
// $password = $_POST["password"];
// $name = mysqli_real_escape_string($con, $name);
// $email = mysqli_real_escape_string($con, $email);
// $password = mysqli_real_escape_string($con, $password);
$created_at = date('Y-m-d');
$queryInsert = "insert into user (name,last_name,user_name,user_type,email,password,created_at) values ('$name','$last_name','$user_name','$user_type','$email','$password','$created_at')";
$resInsert = mysqli_query($con,$queryInsert);
if($resInsert){
$_SESSION['main_notice'] = "Successfully registered, login here!";
header('Location: index.php');
}else{
$_SESSION['main_notice'] = "Some error, try again";
header('Location: '.$_SERVER['PHP_SELF']);
}
}
?>
<?php
if(is_file('include/header.php'))
include_once('include/header.php');
?>
<?php
// define variables and set to empty values
$nameErr = $lnameErr = $userErr = "";
$name = $lname = $user = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate first name
if (empty($_POST["name"])) {
$nameErr = "first Name is required";
}else {
$name = test_input($_POST["name"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
// validate last name
if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
}else {
$lname = test_input($_POST["lname"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
// validate user type
if (empty($_POST["user_name"])) {
$userErr = "Last Name is required";
}else {
$user = test_input($_POST["user_name"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}//end validate tag
?>
<div>
<form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return check()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" value='<?php echo $name ?>'><span style='color: red'>* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" value='<?php echo $lname ?>'><span style='color: red'>* <?php echo $lnameErr;?></span></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user_name" value='<?php echo $user ?>'><span style='color: red'>* <?php echo $userErr;?></span></td>
</tr>
<tr>
<td>User Type</td>
<td>
<select name="user_type" >
<option value="member">Member</option>
<option value="leader">Leader</option>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" ></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password" id="confirm_password" ></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
</table>
</form>
</div>
<script>
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// function check(){
// if(document.getElementById('password').value != document.getElementById('confirm_password').value ){
// alert('password not match');
// return false;
// }else{
// return true;
// }
// }
</script>
<?php
if(is_file('include/footer.php'))
include_once('include/footer.php');
?>
Am not sure if am missing something, but when i send the form without any input, it process it on database. And if i put input in just name field, it just refresh and go blank, even the value data doesn't work idea.
I hope have given enough information for your help, please if any question do ask me.
Thanks in advance
The order of your code seems like it may be the issue. You are checking if the $_POST['submit'] is set and then performing your database operations before the section of code which carries out validation. The section which sets the values to empty should come first, the you want to check if $_POST['submit'] is set, and if it is you THEN do the validation within the if statement. So quickly in pseudocode:
include PHP files
check if user is already logged in
initialise variables
if submit is set {
Validate the input
if valid {
Submit to database
} else {
return error messages as needed
}
}
I hope this helps
EDIT:
$stmt = $con->prepare("INSERT INTO user (name, last_name, user_name, user_type, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $name, $last_name, $user_name, $user_type, $email, $password, $created_at);
$stmt->execute();
$stmt->close();
$con->close();
Also, noticed a few more issues with your other code which may cause you problems.
In the input checks, you are setting variables like $nameErr if the field is invalid. Once you've sorted the code order out though you may find that you have to introduce a check for whether or not you actually have an error at the end of the validation or it will attempt to execute the database section anyway.
The error variables are echo'd to the page but if the all the inputs were acceptable, none of these variables will be defined and PHP might throw errors
Reorganise the code, and then have a careful look at it and think about how the data flow would work when valid and invalid (or null) input is provided.
I think I have properly escaped everything, but yet I'm wondering whether I did the right thing. I remember to read somewhere that we shouldn't filter the input, just the output. In my case, does it mean that I shouldn't use the function sanitize anywhere? And just stick to prepare statements and htmlscpecialchars?
<?php
#Connection to the database
function dbcon (){
try{
$db = new PDO('mysql:dbname=php_test;host=localhost','root','mysql');
}
catch (PDOException $e){
echo $e->getMessage();
exit();
}
return $db;
}
#Sanitize the input for preventing hacking attempts
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
#Get the list of countries from the DB
function getCountries() {
$db = dbcon();
$query = "SELECT country FROM countries";
$stmt = $db->prepare($query);
$stmt->execute();
$countries = "";
while ($row = $stmt->fetch()) {
$countries .= '<option value= "'.$row['country'].'">'.$row['country'].'</option>';
}
return $countries;
}
$name = $email = $password = $password2 = $country = "";
$validForm = True;
#If it's a submission, validate the form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$db = dbcon();
#Name validation
$name = sanitize($_POST["name"]);
if ((strlen($name) < 2) || (strlen($name) > 50)) {
echo "<span style=\"color: #FF0000;\"> Name must have between 2 and 50 characters </span> <br>";
$name = "";
$validForm = False;
}
#Email validation
$email = sanitize($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span style=\"color: #FF0000;\"> Check the format of the email </span> <br>";
$email = "";
$validForm = False;
}
else { #If it's a valid email, check whether or not it's already registered
$query = "SELECT email FROM users;";
$stmt = $db->prepare($query);
$stmt->execute();
$found = False;
while (($row = $stmt->fetch()) and (!$found)) {
if ($row["email"] == $email) {
$found = True;
}
}
if ($found) {
echo "<span style=\"color: #FF0000;\"> This email is already registered </span> <br>";
$email = "";
$validForm = False;
}
}
#Password validation
$password = sanitize($_POST["pass1"]);
if ((strlen($password) < 6) || (strlen($password) > 20)) {
echo "<span style=\"color: #FF0000;\"> Password must have between 6 and 20 characters </span> <br>";
$validForm = False;
}
else { #If it's a valid password, check whether or not both passwords match
$password2 = sanitize($_POST["pass2"]);
if ($password != $password2) {
echo "<span style=\"color: #FF0000;\"> Passwords don't match </span> <br>";
$validForm = False;
}
#If passwords match, hash the password
else {
$password = password_hash($password, PASSWORD_DEFAULT);
}
}
#We don't need to validate country because it's retrieved from the DB, but we sanitize it just in case a hacker modified the POST using a proxy
$country = sanitize($_POST["country"]);
#All checks done, insert into DB and move to success.php
if ($validForm) {
$query = "INSERT INTO users VALUES(:name, :email, :password, :country);";
$stmt = $db->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':country', $country);
$stmt->execute();
header("Location: success.php");
}
}
?>
<html>
<head>
</head>
<body>
<!-- Submitting to this very file -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table>
<tr> <!-- Name -->
<td><label for="name">Name:</label></td>
<td><input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>" required /></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Between 2 and 50 characters</td>
</tr>
<tr> <!-- Email -->
<td><label for="email">Email:</label></td>
<td><input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>" required/></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Must be a valid address</td>
</tr>
<tr> <!-- Password -->
<td><label for="pass1">Password:</label></td>
<td><input type="password" name="pass1" required/></td>
<td><span style="color: #FF0000;">*</span> </td>
<td>Between 6 and 20 characters</td>
</tr>
<tr> <!-- Confirm password -->
<td><label for="pass2">Confirm password:</label></td>
<td><input type="password" name="pass2" required/></td>
<td><span style="color: #FF0000;">*</span></td>
<td>Must be the same as the password</td>
</tr>
<tr> <!-- Country -->
<td><label for="country">Country:</label></td>
<td><select name="country"> <?php echo getCountries(); ?></select></td>
<td><span style="color: #FF0000;">*</span></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Its all done with PDO::prepare
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
and there is anther alternate
PDO::quote
PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.
To know about XSS Injection Read this Answer too
One thing I always use when cleaning data entered by the user is to use strip_tags()...
Specially if the content is to be echoed at some point... you dont want to make easy to inject scripts using your forms.
Try to type <script>alert("hello");</scirpt> in one of the text element and submit...
I'm using this code to validate my my html form and I now need to add the form data into a table in mysql. How do I proceed I know the basics of creating a connection and sql databases but since I've already used the form's submit button i don't know how to get the data to a place where I can insert it again
<?php
// define variables and initialize with empty values
$nameErr = $passErr = $emailErr =$cpassErr="";
$name = $pass = $cpass = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$nameErr = "Enter Username";
}
else {
$name = $_POST["username"];
}
if (empty($_POST["password"])) {
$passErr = "Enter password";
}
else {
$pass = $_POST["password"];
}
if (empty($_POST["cpassword"])) {
$cpassErr = "Retype password";
}
else {
$cpass= $_POST["cpassword"];
}
if (empty($_POST["email"])) {
$emailErr = "Enter email";
}
else {
$email = $_POST["email"];
}
}
?>
<html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table border="0" cellspacing="20">
<tbody>
<tr>
<td>Username:</td>
<td><input type="text" name="username" accept="" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" accept="" value="<?php echo htmlspecialchars($pass);?>">
<span class="error"><?php echo $passErr;?></span></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="text" name="cpassword" accept=""value="<?php echo htmlspecialchars($cpass);?>">
<span class="error"><?php echo $cpassErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" accept="" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Code for the connection
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="LSDB";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$u=$_POST['username'];
$p=$_POST['password'];
$e=$_POST['email'];
$ph=$_POST['phone'];
$sql="INSERT INTO register (username,password,email,phone)
VALUES
('$u','$p','$e','$ph')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
first off i would suggest you escaping the inputs.
also worth noting you could use prepared statements and object oriented way of mysqli as most of the documents on OO are clearer than the procedural way.
like :
<?php
$u=striptags($_POST['username']);
$p=striptags($_POST['password']);
$e=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$ph=(int)$_POST['phone'];
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO register (username,password,email,phone) VALUES (?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssi", $u, $p, $e, $ph);
$stmt->execute();
$mysqli->close();
?>
it would not also hurt using hash on your password like :
<?php
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$passh = crypt($pass, '$6$'.$salt);
?>
do note that you will need to store the salt in mysql also so you can compare it later
so with these your passwords are safer and if your database gets stolen the passwords will remain hashed.
When the user submits the form, if the validation was successful, then you should execute a process function, where you can place as much instructions as you need, including storing the data in a database, or printing it in an auto-generated webpage. Everything you need.
In another order of things, looks like that code of you is too simple and hence vulnerable to cross-site scripting. You should not only validate if the fields are empty or not, but also you should use some regular expressions and the function preg_match( ) to filter which characters are entered. The best protection is to allow the user enter only the characters that are needed in each field, and not any others than those.
Example on how to handle the logic of the form:
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
// The data sent is valid, hence process it...
process_form();
}
} else {
// The form has not been sent, hence show it again...
show_form();
}
i got a problem on my validation script using php; when the user only fills out username form and emptied the password it still logs the user in it should show the user that the password field is blank error. i'm kinda new to php and i'm hoping you can help me. thanks!
here's my code for checking login
<?php
$usernameErr = $passwordErr = "";
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST['username']))
{$usernameErr = "Username is required.";}
else
{$username =($_POST['username']);}
if (empty($_POST['password']))
{$passwordErr = "Password is required.";}
else
{$password =($_POST['password']);}
}
?>
<body>
<div id="header" align="center">
<h1>PT. Sumber Urip Alfindo</h1>
</div>
<br/>
<div id="content" align="center">
<form id="login" name="login" method="post" action="checklogin.php">
<table>
<tr>
<td>Username</td>
<td></td>
<td><input name="username" type="text" id="username"><span class="error"><?php echo $usernameErr;?></span></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input name="password" type="password" id="password"><span class="error"><?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="submit" value="Login"></td>
</tr>
</table>
</form>
<?php
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1 && $username="admin")
{
header("location:mainadmin.php");
}
else if($count==1)
{
header("location:main.php");
}
else
{
echo "Wrong username or password";
}
?>
Before anyone moans, I'm not replacing mysql with mysqli/PDO to answer the question. Yes it's wrong that it's used but it's not related to the question.
Correct model: if (there is not an error) { log the person in } else { do something else}.
Your model: check for errors. log the user in anyway.
This is what you're doing now
// checking stuff
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST['username']))
{$usernameErr = "Username is required.";}
// blah blah check check check
}
// don't bother considering the error, just log them in anyway
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
// etc
But what you need to do is this:
// check for errors and store them
$errors=array(); // create an empty array to store errors
if (empty($_POST['username'])){
$errors['usernameErr'] = "Username is required."; // add an error
}else{
$username =($_POST['username']);
}
if (empty($_POST['password'])){
$errors['passwordErr'] = "Password is required."; // add an error
}else{
$password =($_POST['password']);
}
// etc etc
// check if there were any errors anywhere along the way
// and if not, proceed with login
if (!count($errors)) { // check there are no errors
$sql="SELECT * FROM $tbl_name WHERE usrname='$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
// etc etc
}else{
// if there were errors do something else
echo implode("<br />", $errors); // output the errors however you like
}
Try this for a start
<?php
/* validate form first */
if (!empty($_POST['username']))
{ $username = $_POST['username'];
}
else{ echo "Username is required."; }
if (!empty($_POST['password']))
{ $password = $_POST['password'];
}
else{ echo "password is required."; }
/* Do the queries second i.e */
SELECT * FROM Persons WHERE username='' AND password ='';
?>
hi,You should describe your question clearly,I have read your code and checked it ,when i not fills out password,it was really display Password is required.
general validation method is as follows:
if(empty($_POST['username'])){
$usererror = '...';
return false;
}else{
$username = $_POST['username'];
}
if(empty($_POST['password'])){
$passerror = '...';
return false;
}else{
$password = $_POST['password'];
}
The best way to handle error validation is to use same variable, especially if you have many input form data
$username = $_POST['username'];
$password = $_POST['password'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($username == '') {
$error_msg[]= 'Username is required';
} else if ($password == '') {
$error_msg[]= 'Password is required';
}
}
if (!empty($error_msg)) {
$ERROR_MSG = implode($error_msg);
exit;
}