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
}
?>
Related
I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>
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!
I already browsed the Internet, but could not find and understand any solution provided.
Basically, I created (or rather copied some scripts from the Internet) and tried to work on the scripts to make a registration page. I'm using PHP, Mysql and XAMPP. The connection is fine already.. I tested some data inputs on a basic form etc.
but My problem is, after I messed around with the scripts, I managed to insert data into the table (peekdoordb)...all the hashing and validation form worked..except that, the form keeps submitting data into the DB even when data is wrong or the field is empty. After I messed around again, then the problem arises. The error is on " $stmt->bindValue(':name', $name);"
I keep getting this error on browser;
Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on
line 194
and
Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194
The registration.php (registration page) include 2 files which are connect.php and password.php but I never messed anything with those 2 files, because before that, data could be submitted only the problem was with the form, data keeps inserting in DB like I mentioned previously. But the main problem now is about this error.
<?php
//register.php
/**
* Start the session.
*/
session_start();
//Include password_compat library.
require 'lib/password.php';
//Include MySQL connection.
require 'connect.php';
//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError ="";
$name = $telno = $username = $pass = "";
//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null ;
$telno = !empty ($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true; // Boolean - Set to true b4 validating
//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if(isset($_POST['register'])){
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
if (empty($_POST["name"])) {
$nameError = "Name is required";
}else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["telno"])) {
$telnoError = "Tel number is required";
} else {
$telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/^[a-zA-Z ]*$/",$telno)) {
$telnoError = "Invalid tel no format";
}
}
if (empty($_POST["username"])) {
$usernameError = "username is required";
} else {
$username = test_input($_POST["username"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameError = "Only letters and email syntax required";
}
}
if (empty($_POST["password"])) {
$passwordError = "passworde is required";
} else {
$pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/",$pass)) {
$passwordError = "Only password letter syntax";
}
}
//*******************************************************************
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if($row['num'] > 0){
die('That username already exists!');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
}
//If the signup process is successful.
elseif($formValid){
//******************************ppppp
//Bind our variables.
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
$stmt = $pdo->prepare($sql);
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
//Execute the statement and insert the new account.
$result = $stmt->execute();
//What you do here is up to you!
echo 'Thank you for registering with our website.';
}
else {
die('something wrong!');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<style type="text/css">
.lucida {
font-family: "MS Serif", "New York", serif;
}
body form table {
font-weight: bold;
}
</style>
</head>
<body>
<h1> </h1>
<h1> </h1>
<h1 align="center"> Register</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div align="center">
<table width="800" border="0">
<tr>
<td width="404" class="lucida"><div align="right">Name :</div></td>
<td width="386"><input class="input" name="name" type="text" value="<?PHP print $name ; ?>">
<span class="error">* <?php echo $nameError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Contact Number :</div></td>
<td><input class="input" name="telno" type="text" value="<?PHP print $telno ; ?>">
<span class="error">* <?php echo $telnoError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Email (Username) :</div></td>
<td><input class="input" name="username" type="text" value="<?PHP print $username ; ?>">
<span class="error">* <?php echo $usernameError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Password :</div></td>
<td><input class="input" name="password" type="text" value="">
<span class="error">* <?php echo $passwordError;?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
</table>
<input type="submit" name="register" value="Register">
<br>
</div>
</button>
</form>
</body>
</html>
the form keeps submitting data into the DB even when data is wrong or the field is empty
You are checking $formValid in the wrong place. Your conditions can be summarized as follows:
$formValid = true;
if (isset($_POST['register'])) {
} else if ($formValid) {
} else { ...
As above, if $_POST['register'] is not set (e.g. when loading the registration form) your code will execute whatever is in the second if statement. Your condition structure should be amended to include the form validity check inside the first condition:
$formValid = true;
if (isset($_POST['register'])) {
// validation stuff goes here
if ($formValid) {
//database insert goes here
}
else {
//invalid data. Tell the user
}
}
Also as a rule, you should assume any data from the user is invalid unless proven otherwise i.e. $formValid should be false initially.
Notice: Undefined variable: stmt in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 19
Fatal error: Call to a member function bindValue() on a non-object in C:\xampp\htdocs\eventsite\TMP1kjqc3x.php on line 194
You are trying to use a variable $stmt that has not been defined within the scope of else if($formValid). The same goes for $sql. Any variable must be set before it is used. The order should be:
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
Try this -
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$stmt->execute();
You have bindValue before prepare your statement so you are getting this error. Can prepare your statement below your $sql variable then bind your value. This is working for me.
UPDATED ANSWER
<?php
//register.php
/**
* Start the session.
*/
session_start();
//Include password_compat library.
require 'lib/password.php';
//Include MySQL connection.
require 'connect.php';
//define variables and define to null.
$nameError = $telnoError = $usernameError = $passwordError = "";
$name = $telno = $username = $pass = "";
//Retrieve the field values from registration form.
$name = !empty($_POST ['name']) ? trim($_POST['name']) : null;
$telno = !empty($_POST ['telno']) ? trim($_POST['telno']) : null;
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true; // Boolean - Set to true b4 validating
//If the POST var "register" exists ( the submit button), then I can
//assume that the user has submitted the registration form.
if (isset($_POST['register'])) {
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
if (empty($_POST["name"])) {
$nameError = "Name is required";
$formValid = false;
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameError = "Only letters and white space allowed";
$formValid = false;
}
}
if (empty($_POST["telno"])) {
$telnoError = "Tel number is required";
$formValid = false;
} else {
$telno = test_input($_POST["telno"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/^[a-zA-Z ]*$/", $telno)) {
$telnoError = "Invalid tel no format";
$formValid = false;
}
}
if (empty($_POST["username"])) {
$usernameError = "username is required";
$formValid = false;
} else {
$username = test_input($_POST["username"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/", $username)) {
$usernameError = "Only letters and email syntax required";
$formValid = false;
}
}
if (empty($_POST["password"])) {
$passwordError = "passworde is required";
$formValid = false;
} else {
$pass = test_input($_POST["password"]);
// check name only contains letters and email syntax
if (!preg_match("/^[a-zA-Z ]*$/", $pass)) {
$passwordError = "Only password letter syntax";
$formValid = false;
}
}
//*******************************************************************
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if ($row['num'] > 0) {
$usernameError = 'That username already exists!';
$formValid = false;
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
//$passwordHash = $pass;
if ($formValid) {
//******************************ppppp
//Bind our variables.
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (name, telno, username, password) VALUES (:name, :telno, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $name);
$stmt->bindValue(':telno', $telno);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//What you do here is up to you!
echo 'Thank you for registering with our website.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<style type="text/css">
.lucida {
font-family: "MS Serif", "New York", serif;
}
body form table {
font-weight: bold;
}
</style>
</head>
<body>
<h1> </h1>
<h1> </h1>
<h1 align="center"> Register</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div align="center">
<table width="800" border="0">
<tr>
<td width="404" class="lucida"><div align="right">Name :</div></td>
<td width="386"><input class="input" name="name" type="text" value="<?PHP print $name; ?>">
<span class="error">* <?php echo $nameError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Contact Number :</div></td>
<td><input class="input" name="telno" type="text" value="<?PHP print $telno; ?>">
<span class="error">* <?php echo $telnoError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Email (Username) :</div></td>
<td><input class="input" name="username" type="text" value="<?PHP print $username; ?>">
<span class="error">* <?php echo $usernameError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right">Password :</div></td>
<td><input class="input" name="password" type="text" value="">
<span class="error">* <?php echo $passwordError; ?></span></td>
</tr>
<tr>
<td class="lucida"><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><div align="right"></div></td>
<td> </td>
</tr>
</table>
<input type="submit" name="register" value="Register">
<br>
</div>
</button>
</form>
</body>
</html>
having a bit of trouble with my login / reg forms
Basically when i register (create new user) it takes me to the login.php script and not the register script.
The login form is in the "header.php" page so its at the top of every page including the register form. But dont think that would be an issue?
Register form
<?php
include("config.php");
include("header.php");
?>
<div id="contentwrap">
<form name="myuserform" method="POST" action="register.php" onsubmit="return validateForm();">
<tr class='alt'>
<td>email address: <td><input type="text" name="email">
<tr class='alt'>
<td>Password: <td><input type="password" name="password">
<tr class='alt'>
<td>Your name: <td><input type="text" name="username">
<tr class='alt'>
<td><input type="submit" name="adduser" value="Sign me up!">
</form>
</div>
Register.php
<?php
if (isset($_POST['adduser']))
{
$error = "";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$md5_pass = md5($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
if (!isset($username) || empty($username) ||
!isset($password) || empty($password) ||
!isset($email) || empty($email))
{
$error = "All fields must be filled out";
}
else if (user_exists($connection, $username))
{
$error = "Username already registered";
}
else if (strlen($password) < 6)
{
$error = "Password must be at least 6 characters";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // check if email looks valid
{
$error = "Please enter a valid email";
}
if ($error == "")
{
//$query = "INSERT INTO users (email, password, username) VALUES ('{$email}','{$md5_pass}','{$username}')";
$query = "INSERT INTO users (username, password, email) VALUES ('{$username}','{$md5_pass}','{$email}')";
$result = mysqli_query($connection, $query);
if ($result)
echo " <b>Registered successfully!</b><br/>Please return to the <a href='index.php'>index</a> to login.";
else
$error = "Unable to create new user";
}
if ($error != "") // redo error string check since the last block may have set it
{
echo "Error: {$error}. Please return to the previous page.";
}
exit();
}
?>
Login.php
<?php
include("config.php");
if (isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) >= 1)
{
$row = mysqli_fetch_array($res);
if($row['rank'] == "banned")
{
echo "You have been banned from the site.";
exit();
}
$_SESSION['uid'] = $row['userid'];
$_SESSION['username'] = $row['username'];
if($row['rank'] == "admin")
$_SESSION['is_admin'] = true;
header("Location: index.php");
exit();
}
else
{
echo "Username/password invalid. Return to the <a href='index.php'> home </a>page";
exit();
}
}
echo "Something went wrong, try again"; <--- this is the result im getting
?>
here is the login form (apart of header.php)
<?php
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
echo "<form action='login.php' method='post'>
Username: <input type='text' name='username' Placeholder='Username' style='width:100px;'/>
Password: <input type='password' name='password' Placeholder='Password' style='width:100px;' />
<input type='submit' name='submit' value='Log In' />";
echo "<div id='freeman'>
<a href='signup.php'> <img src='images/register.jpg' width='60px' height='60px' /> </a>
</div>";
} else {
echo "You are logged is as {$_SESSION['username']} • <a href='logout.php'>Logout</a>";
}
?>
The problem that when you register your not opening a session to consider the user as logged and acquire a session for him.
The other issue your not checking in your login script if the user already have a session which implies that he is already logged in
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;
}