How to check value in mysql with php pdo connection? - php

I'm a totally beginner in php, so I need help with my registration script. I have 4 fields, 1 username (which is in the back transformed in an email address), 1 current email address of owner and 2 password fields. Registration is working, I only want to add the validation of username in case exists or not. My problem is that I don't know where and how to do it, should I create a function? How? I wanted to keep it simple so I didn't create any kind of session, is it possible without, as is?
here is the code:
<?php
$host = '127.0.0.1';
$dbuser = 'reguser';
$dbpass = 'regpass';
$dbn = 'regform';
$conn = new PDO("mysql:host=$host;dbname=$dbn", $dbuser, $dbpass);
$RegScrIdErr = $RegScrIdChrErr = $OwnAddressErr = $Password1Err = $Password2Err = $PasswordMErr = "";
$formValid = true;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["RegScrId"])) {$RegScrIdErr = "Userame is required"; $formValid = false;}
else {$RegScrId = check_input($_POST["RegScrId"]);
if (!preg_match("/^[a-zA-Z0-9]*$/",$RegScrId)){$RegScrIdErr = "Only letters and numbers allowed"; $formValid = false;}
}
if (empty($_POST["OwnAddress"])) {$OwnAddressErr = "Email is required"; $formValid = false;}
else {$OwnAddress = check_input($_POST["OwnAddress"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$OwnAddress)){$OwnAddressErr = "Invalid email format"; $formValid = false;}
}
if (empty($_POST["Password1"])) {$Password1Err = "Password field can't be empty!"; $formValid = false;}
else {$Password1 = check_input($_POST["Password1"]);}
if (empty($_POST["Password2"])){$Password2Err = "Password Confirmation can't be empty!"; $formValid = false;}
else {$Password2 = check_input($_POST["Password2"]);
if ($_POST["Password1"]!= $_POST["Password2"]) {$PasswordMErr = "Password does not match!"; $formValid = false;}
}
if ($formValid) { header('Location: index.html'); }
}
function check_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$RegScrIdFull = "$RegScrId#RegScrserver.com";
$userIp = $_SERVER['REMOTE_ADDR'];
$hash = hash('sha1', $Password1);
FUNCTION createSalt(){
$text = md5(uniqid(rand(), TRUE));
RETURN substr($text, 0, 3);
}
$salt = createSalt();
$PasswordSec = hash('sha256', $salt . $hash);
if ($formValid) {
$qry = $conn->PREPARE('INSERT INTO userlist (RegScrId, password, email, userIp, salt) VALUES (?, ?, ?, ?, ?)');
$qry->EXECUTE(array($RegScrIdFull, $hash, $OwnAddress, $userIp, $salt));
$conn = null;
}
?>
<div id="wrapper">
<header><img src="img/logo3.png" width="170" height="110" /><br><br>
</header><br>
<div id="section_contact">
<form name="register" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"><br />
<table width="850" border="0" id="tb-form">
<tr>
<td class="tb-form-left" colspan="2"><h4><strong>Sign Up</strong></h4><br /></td>
</tr>
<tr>
<td class="tb-form-left"><input type="text" name="OwnAddress" maxlength="30" placeholder=" Own Email Address" value="<?php echo $ $OwnAddress;?>" /><span class="error"><?php echo $OwnAddressErr;?></span></td>
</tr>
<tr>
<td class="tb-form-left"><input type="text" class="RegScrIdPic" maxlength="28" name="RegScrId" id="email" placeholder=" RegScrserver Username" value="<?php echo $RegScrId;?>" /><span class="error"><?php echo $RegScrIdErr;?><?php echo $RegScrIdChrErr;?></span></td>
</tr>
<tr>
<td class="tb-form-left"><input type="password" name="Password1" placeholder=" Enter Password"/><span class="error"><?php echo $Password1Err;?></span></td>
</tr>
<tr>
<td class="tb-form-left"><input type="password" name="Password2" placeholder=" Confirm Password" /><span class="error"><?php echo $Password2Err;?><?php echo $PasswordMErr;?></span></td>
</tr>
<tr>
<td class="tb-form-left"><input id="form-btn" type="submit" value="Create Account" /></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>

if you want implements validation when username exist in your database you first should ask database if username really exists. Before your insert you should use SELECT query
$sth = $conn->prepare('SELECT id FROM users WHERE username=:username');
$sth->bindValue(':username',$username,PDO::PARAM_STR);
sth->execute();
while($row = $sth->fetch()){
/// ....... here you get username
}
// if in $row you get username you can use now validation for example
if(!empty($row)){
my_validation_function();
}
else{
// we dont want approaching form so we redirect customer to some page
header('location: some url');
}
if ($formValid) {
$qry = $conn->PREPARE('INSERT INTO userlist (RegScrId, password, email, userIp, salt) VALUES (?, ?, ?, ?, ?)');
$qry->EXECUTE(array($RegScrIdFull, $hash, $OwnAddress, $userIp, $salt));
$conn = null;
}

Related

How to join PHP with HTML forms to make a working page?

I stuck at creating a form that will work i.e. take user input and insert into DB.
I have a code, that i know works on its own. the PHP code when run bare with hard-coded values, works. FORM without PHP works.
When I put it all together, nope. I would really appreciate any input!
P.S. I know some names might be odd and it overall very simple, but I don't want to spend time on something that might not even work, and I really have to make it working, preferably yesterday.
HTML:
<?php require 'insert.php';?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Absolute classes registration</h2>
<p><span class = "error">* required field.</span></p>
<form method = "post" action = "<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Username:</td>
<td><input type = "text" name = "username">
<span class = "error">* <?php echo $usernameErr;?></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td> <input type = "text" name = "password">
<span class = "error"><?php echo $passwordErr;?></span>
</td>
</tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</table>
</form>
</body>
</html>
PHP:
<?php
require 'dbconn.php';
// define variables and set to empty values
$usernameErr = $emailErr = $passwordErr = "";
$username = $email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Name is required";
}else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password required";
}else {
$password = test_input($_POST["password"]);
}
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";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO User_tbl (username, password, email) VALUES (:username, :password, :email)";
$stmt = $pdo->prepare($sql);
//$stmt->bindParam(':token',$token,PDO::PARAM_STR);
$stmt->bindParam(':username',$username,PDO::PARAM_STR);
$stmt->bindParam(':password',$password,PDO::PARAM_STR);
//$stmt->bindParam(':fname',$user_fname,PDO::PARAM_STR);
//$stmt->bindParam(':lname',$user_lname,PDO::PARAM_STR);
//$stmt->bindParam(':telephone',$user_telephone,PDO::PARAM_STR);
$stmt->bindParam(':email',$email,PDO::PARAM_STR);
//$token = '436546brty546b45y'; // generate unique token
$username = $_POST["username"];
$password = $_POST["password"]; //encrypt password
//$fname = $_POST['fname'];
//$lname = $_POST['lname'];
//$telephone = $_POST['telephone'];
$email = $_POST["email"];
$stmt->execute();
$stmt->close();
//header('location: welcome.php');
?>
Conn:
<?php
$servername = 'redacted';
$login = 'redacted';
$password = 'redacted';
$DBname = 'redacted';
// Establish database connection.
$pdo = new PDO("mysql:host=$servername;dbname=$DBname", $login, $password);
//print error or success
if ($pdo->connect_error) {
die("Connection failed."/* . $conn->connect_error*/);
}
if ($pdo) {
echo "Connected successfully";
}
?>

Error on bindValue

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>

Are the variables in this code properly escaped?

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...

user_login and password_login correct, but are not working PDOPHP

I am trying to get my login script to work using PDO. The problem I am having is that when a user types in his/her username and passsword, it goes to the section of the code where it says it is incorrect, even if the password is correct. What can I do to fix this, and where can I implement the PDO error to show up to possibly help diagnose the problem.
The Login Script from index.php
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$password_login=md5($password_login);
$db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
$db->prepare($sql);
if ($db->execute(array(
':user_login' => $user_login,
':password_login' => $password_login))); {
if ($sql->rowCount() > 0){
while($row = $sql->fetch($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
exit();
}
}
}
?>
index.php
<? include("inc/incfiles/header.inc.php"); ?>
<?
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; //Password 2
$d = ""; //Sign up Date
$u_check = ""; //Check if username exists
//registration form
$fn = #$_POST['fname'];
$ln = #$_POST['lname'];
$un = #$_POST['username'];
$em = #$_POST['email'];
$em2 = #$_POST['email2'];
$pswd = #$_POST['password'];
$pswd2 = #$_POST['password2'];
$d = date("y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$statement = $db->prepare('SELECT username FROM users WHERE username = :username');
if ($statement->execute(array(':username' => $un))) {
if ($statement->rowCount() > 0){
//user exists
echo "Username already exists, please choose another user name.";
exit();
}
}
//check all of the fields have been filled in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
//check that passwords match
if ($pswd==$pswd2) {
//check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
}
else
{
//check the length of the password is between 5 and 30 characters long
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$sql = 'INSERT INTO users (username, first_name, last_name, email, password, sign_up_date)';
$sql .= 'VALUES (:username, :first_name, :last_name, :email, :password, :sign_up_date)';
$query=$db->prepare($sql);
$query->bindParam(':username', $un, PDO::PARAM_STR);
$query->bindParam(':first_name', $fn, PDO::PARAM_STR);
$query->bindParam(':last_name', $ln, PDO::PARAM_STR);
$query->bindParam(':email', $em, PDO::PARAM_STR);
$query->bindParam(':password', $pswd, PDO::PARAM_STR);
$query->bindParam(':sign_up_date', $d, PDO::PARAM_STR);
$query->execute();
$query=$db->prepare($sql);
$array = array(
':username' => $un,
':first_name' => $fn,
':last_name' => $ln,
':email' => $em,
':password' => $pswd,
':sign_up_date' => $d);
$query->execute($array);
die("<h2>Welcome to Rebel Connect</h2>Login to your account to get started.");
}
}
}
else {
echo "Your passwords do not match!";
}
}
else
{
echo "Please fill in all fields!";
}
}
else {
echo "Your e-mails don't match!";
}
}
?>
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$password_login=md5($password_login);
$db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
$db->prepare($sql);
if ($db->execute(array(
':user_login' => $user_login,
':password_login' => $password_login))); {
if ($sql->rowCount() > 0){
while($row = $sql->fetch($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
exit();
}
}
}
?>
<table class="homepageTable">
<tr>
<td width="60%" valign="top">
<h2>Already a member? Login below.</h2>
<form action="index.php" method="post" name="form1" id="form1">
<input type="text" size="25" name="user_login" id="user_login" placeholder="username" />
<br />
<input type="password" size="25" name="password_login" id="password_login" placeholder="password" />
<br />
<input type="submit" name="button" id="button" value="Login to your account!">
</form>
</td>
<td width="40%" valign="top">
<h2>Sign up below...</h2>
<form action="#" method="post">
<input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
<input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
<input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
<input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
<input type="text" size="25" name="email2" placeholder="Re-enter Email" value="<? echo $em2; ?>">
<input type="password" size="25" name="password" placeholder="password" value="<? echo $pswd; ?>">
<input type="password" size="25" name="password2" placeholder="Re-enter Password" value="<? echo $pswd2; ?>"><br />
<input type="submit" name="reg" value="Sign Up!">
</form>
</td>
</tr>
</table>
</body>
</html>
logout.php
<?
session_start();
session_destroy();
header("Location: index.php");
?>
home.php
<?
session_start();
$user = $_SESSION["user_login"];
//If the user is not logged in
if (!isset($_SESSION["user_login"])) {
header("location: index.php");
exit();
}
else
{
//If the user is logged in
echo "Hi, $user, You're logged in<br />Welcome to what is soon to be your NEWSFEED
Logout?
";
}
?>
header.inc.php
<?
include ("inc/scripts/db_connect.inc.php");
session_start();
if (!isset($_SESSION["user_login"])) {
}
else
{
header("location: home.php");
}
?>
<html>
<head>
<link href="css/main.css" rel="stylesheet" type="text/css">
<title>Rebel Reach - PHS Student Social Network</title>
</head>
<body>
<div class="headerMenu">
<div id="wrapper">
<div class="logo">
<img src="img/find_friends_logo.png">
</div>
<div class="search_box">
<form method="get" action="search.php" id="search">
<input name="q" type="text" size="60" placeholder="Search..." />
</form>
</div>
<div id="menu">
Home
About
Sign Up
Login
</div>
</div>
</div>
<br />
<br />
<br />
<br />
Not an answer but some advice for your code that couldn't fit in the comment. You can greatly reduce your code; actually you shouldn't repeat functionality too often... You can reduce:
$fn = ""; //First Name
$ln = ""; //Last Name
...
$fn = #$_POST['fname'];
$ln = #$_POST['lname'];
...
To half by writting it like this:
$fn = (!empty($_POST['fname'])) ? $_POST['fname'] : '';
$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';
$un = (!empty($_POST['username'])) ? $_POST['username'] : '';
$em = (!empty($_POST['email'])) ? $_POST['email'] : '';
$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';
$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';
$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';
Furthermore, although this would require some other changes, you can reduce that to a couple of lines by writing it in an array like this:
// Retrieve user data
foreach (array('fname', 'lname', 'username', 'email', 'email2', 'password', 'password2') as $Value)
$User[$Value] = (!empty($_POST[$Value])) ? $_POST[$Value] : '';
I think your problem is here:
"SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
When you use PDO prepare method like ? or : do not use single quotation mark (').
correct it like this:
"SELECT id FROM users WHERE username = :user_login AND password = :password_login LIMIT 1";
I hope now it will work!
RE your "Fatal error: call to undefined method PDO::execute() in ... line 110" issue:
"execute()" is a method in PDOStatement, not PDO, which is why your "$db->execute..." blew up.
(I know this should be a comment, but I'm not allowed yet. Sorry)

Login in code will just login with md5 encrypted password

I've created a login + register site. The register page works fine, login too except that when I have to write in my password I have to write in the encrypted version, the md5...
I've done in register page so that their password gets encrypted. How can I make in login page so that they dont need to write their md5 password, just their normal one?
The register.php looks like:
<?
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; // Password 2
$d = ""; // Sign up Date
$u_check = ""; // Check if username exists
//registration form
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['username']);
$em = strip_tags(#$_POST['email']);
$em2 = strip_tags(#$_POST['email2']);
$pswd = strip_tags(#$_POST['password']);
$pswd2 = strip_tags(#$_POST['password2']);
$d = date("Y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
// Count the amount of rows where username = $un
$check = mysql_num_rows($u_check);
if ($check == 0) {
//check all of the fields have been filed in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
// check that passwords match
if ($pswd==$pswd2) {
// check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
}
else
{
// check the maximum length of password does not exceed 25 characters and is not less than 5 characters
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0')");
die("<h2>Welcome to InstaWord!</h2>Login to your account to get started ...");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all of the fields";
}
}
else
{
echo "Username already taken ...";
}
}
else {
echo "Your E-mails don't match!";
}
}
?>
<table class="homepageTable">
<tr>
<td width="60%" valign="top">
<h2>Share your texts!</h2>
<img src="img/animation.gif" width="930">
</td>
<td width="40%" valign="top">
<h2>Sign up</h2>
<form action="#" method="post">
<input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
<input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
<input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
<input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
<input type="text" size="25" name="email2" placeholder="Repeat Email" value="<? echo $em2; ?>">
<input type="password" size="25" name="password" placeholder="Password">
<input type="password" size="25" name="password2" placeholder="Repeat Password"> <br />
<input type="submit" name="reg" value="Sign Up!">
</form>
</td>
</tr>
</table>
</body>
</html>
And the login.php looks like this:
<?php
session_start();
//This displays your login form
function index(){
echo "<form action='?act=login' method='post'>"
."Username: <input type='text' name='username' size='30'><br>"
."Password: <input type='password' name='password' size='30'><br>"
."<input type='submit' value='Login'>"
."</form>";
}
//This function will find and checks if your data is correct
function login(){
//Collect your info from login form
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
//Connecting to database
$connect = mysql_connect("myserver", "username", "password");
if(!$connect){
die(mysql_error());
}
//Selecting database
$select_db = mysql_select_db("database_name", $connect);
if(!$select_db){
die(mysql_error());
}
//Find if entered data is correct
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = mysql_fetch_array($result);
$id = $row['id'];
$select_user = mysql_query("SELECT * FROM users WHERE id='$id'");
$row2 = mysql_fetch_array($select_user);
$user = $row2['username'];
if($username != $user){
die("Username is wrong!");
}
$pass_check = mysql_query("SELECT * FROM users WHERE username='$username' AND id='$id'");
$row3 = mysql_fetch_array($pass_check);
$email = $row3['email'];
$select_pass = mysql_query("SELECT * FROM users WHERE username='$username' AND id='$id' AND email='$email'");
$row4 = mysql_fetch_array($select_pass);
$real_password = $row4['password'];
if($password != $real_password){
die("Your password is wrong!");
}
//Now if everything is correct let's finish his/her/its login
session_register("username", $username);
session_register("password", $password);
echo "Welcome, ".$username." please continue on our <a href=index.php>Index</a>";
}
switch($act){
default;
index();
break;
case "login";
login();
break;
}
?>
Please help me fix this...
You are not using md5 to check while login....
Use $password = md5($_REQUEST['password']); In your login function().
This will take the normal password and check it with encrypted version in database and then will successfully log the user in.
Hope this helps.
You should not apply a strip_tags() to the $_POST['password'], just feed the incoming value to the password hashing function.
To protect your user's passwords, you need to do better than md5 hash the passwords.
You need
a better hashing algorithm: BCrypt hash
add a random salt value
The good news is that you can just use a drop-in library and use that: PHPass
require('PasswordHash.php');
$pwdHasher = new PasswordHash(8, FALSE);
// $hash is what you would store in your database
$hash = $pwdHasher->HashPassword( $_POST['password'] );
// $hash would be the $hashed stored in your database for this user
$checked = $pwdHasher->CheckPassword($_POST['password'], $hash);
if ($checked) {
echo 'password correct';
} else {
echo 'wrong credentials';
}
Encrypt the input password with md5() when you pass the details into sql query while checking correct login details.
$password_encrypt = md5($password);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password_encrypt '");

Categories