PHP and MySQL, issue with form token - php

I am new to PHP and trying to implement a method by which a user can be added to the database, I am following a tutorial and before I went to work, it was working fine, but now, it is stopping at this statement:
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
Is there something I'm missing? Full code:
AddUser.php
<?php
//Begin our session
session_start();
//set a form token
$formToken = md5( uniqid('auth', true) );
//set the session form token
$_SESSION['formToken'] = $formToken;
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Add User</h2>
<form action="addUserSubmit.php" method="post">
<fieldset>
<p>
<label for="Username">Username</label>
<input tupe="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input tupe="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
<input type="submit" value="$rarr; Login" />
</p>
</fieldset>
</form>
</body>
</html>
addUserSubmit.php
<?php
//begin our session
session_start();
//Check if username, password and form token have been sent
if(!isset($_POST['Username'], $_POST['Password'], $_POST['formToken']))
{
$message = 'Please enter a valid username and password';
}
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
//Check the username is the correct length
else if (strlen($_POST['Username']) > 20 || strlen($_POST['Usernamw']) < 4)
{
$message = 'Incorrect Username lenght, please try again';
}
//Check the username only has alpha numeric characters
else if (ctype_alnum($_POST['Username']) != true)
{
$message = "Username must be alpha numeric";
}
else if (ctype_alnum($_POST['Password']) != true)
{
$message = "Password must be alpha numeric";
}
else
{
//Enter the data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = shal($password);
//Connect to the database
$SQLusername = "name";
$SQLpassword = "password";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLusername, $SQLpassword, $SQLhostname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (Username, Password)
VALUES
('$_POST[$username]','$_POST[$password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<p><?php echo $message; ?>
</body>
</html>

There is a typo I think.. Try changing,
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
to:
<input type="hidden" name="formToken" value="<?php echo $formToken; ?>" />

Related

My php code is not working fine. Doesn't check if data matches

I have my pin.php as:
<?php //connection $db_host="localhost"; $db_username="root";
$db_password="";
$connection =
mysql_connect("$db_host","$db_username","$db_password");
if (!$connection){ die("database connection failed: ".
mysql_error()); }
session_start([
'cookie_lifetime' => 120, ]); //Start a new session (2 minutes)
?> <html> <head> <title>Check Result</title> </head> <body> Check
Result<br /><br /> <?php $dbname = "db";
$db_sel=mysql_select_db($dbname,$connection);
if(!$db_sel) {
echo "<h1>Unable to Connect to the Database</h1><hr />";
exit();
}
// Check submit button click
if(isset($_REQUEST['submit'])) { if (!empty($_POST['uname']) &&
!empty($_POST['pass'])) { $serial =
stripslashes(trim($_POST['serial'])); $pin =
stripslashes(trim($_POST['pin']));
$sign = mysql_query("SELECT * FROM pin WHERE serial='$serial' AND
pin='$pin'");
$no=mysql_num_rows($sign); //if username and password matches if($no!=0)
{
$_SESSION['serial']=$serial; $_SESSION['pin']= $pin;
$logintimes=mktime();
$ipaddress=$_SERVER['REMOTE_ADDR'];
//Redirects the user to the password protected page
header("Location: result.php");
exit();
} else{ // if invalid serial/pin echo "Invalid";
} } else{ // if empty on submit echo "empty";//empty”; } } ?>
<form action="print.php" method="post"> Serial Number: <input
type="text" name="serial" value="" class="style3" size="18"/><br />
PIN: <input type="hide" name="pin" class="style3" size="18"/><br />
<input type="submit" name="submit" value="Login" class="button" />
</form> </body> </html>
and my result.php as:
<?php
session_start([ 'cookie_lifetime' => 120, ]); if(isset($_SESSION['serial']) && ($_SESSION['pin'])) { ?>
<h3>Welcome</h3> <div> This is your result...<br /> <?php
$logintimes=mktime();
$ipaddress=$_SERVER['REMOTE_ADDR'];
echo $logintimes; echo $ipaddress; ?> </div> <?php session_destroy(); } else { //Redirects the user to the login page
if he is not logged in header("Location: index.php"); } ?>
On submit, it's still accessing result.php without checking if serial=$serial AND pin=$pin
Guys I looked into this a little. tried to clean it up so its more readable, and I would suggest at least templating out the page and use replace('tag',function()) method to enter data into the template.
<?php //connection $db_host="localhost"; $db_username="root";
$db_password="";
$connection = mysql_connect("$db_host","$db_username","$db_password");
if (!$connection){
die("database connection failed: ".mysql_error());
}
session_start([
'cookie_lifetime' => 120, ]); //Start a new session (2 minutes)
?> <html> <head> <title>Check Result</title> </head> <body> Check Result<br /><br /> <?php
$dbname = "db";
$db_sel=mysql_select_db($dbname,$connection);
if(!$db_sel) {
echo "<h1>Unable to Connect to the Database</h1><hr />";
exit();
}
// Check submit button click
if( isset($_REQUEST['submit'])) {
if (!empty($_POST['uname']) && !empty($_POST['pass'])) {
$serial = stripslashes(trim($_POST['serial']));
$pin = stripslashes(trim($_POST['pin']));
$sign = mysql_query("SELECT * FROM pin WHERE serial='$serial' AND pin='$pin'");
while ($row = mysql_fetch_array($sign, MYSQL_NUM)) {
$_SESSION['serial'] = $serial;
$_SESSION['pin'] = $pin;
$logintimes = mktime();
$ipaddress = $_SERVER['REMOTE_ADDR'];
//Redirects the user to the password protected page
header("Location: result.php");
exit();
} // if success above will exit, else get to the below error note.
echo "Invalid";
}
} else { // if empty on submit
echo "Please enter you name or password FooL";//empty”;
}
}
?><form action="print.php" method="post"> Serial Number: <input type="text" name="serial" value="" class="style3" size="18"/><br /> PIN: <input type="hide" name="pin" class="style3" size="18"/><br /> <input type="submit" name="submit" value="Login" class="button" /> </form></body> </html>
I didn't test it, but you can see I replaced the n$no with a row pull, the point you need to understand is the row count will be zero because you haven't yet pulled the row, the point is still at the start.

Get Always Validation Error in Login Page Even Correct Data is Given

Following is the Code for LOGIN page used with html & php.
The problem I am facing is that , even after submitting correct information Login is failed .
Is there any problem with the query I used?
<html>
<head>
<title>login</title>
<link rel="stylesheet" href="css/insert.css" />
</head>
<body>
<div class="maindiv">
<!--HTML form -->
<div class="form_div">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <!-- method can be set POST for hiding values in URL-->
<h2>Login Form</h2>
<label>Email:</label><br />
<input class="input" type="email" name="mail" />
<br />
<label>Password:</label><br />
<input class="input" type="text" name="pass" />
<br />
<input class="submit" type="submit" name="submit" value="Login" />
PHP
//Selecting Database from Server
$db = mysql_select_db("tanni", $connection);
if(isset($_POST['submit'])){
//Fetching variables of the form which travels in URL
$mail = $_POST['mail'];
$pass = $_POST['pass'];
if($mail!=''&&$pass!=''){
$query=mysql_query("SELECT* FROM user WHERE mail='".$mail."' and pass='".$pass."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res){
$_SESSION['mail']=$mail;
}else {
echo'You entered username or password is incorrect';
}
}else{
echo'Enter both username and password';
}
}
//Closing Connection with Server
mysql_close($connection);
?>
</form>
</div>
<div class="formget"><a href=http://www.formget.com/app><img src="formget.jpg" alt="Online Form Builder"/></a>
</div>
</div>
</body>
</html>
What is the problem in the code?
Need space between select and * at SELECT* FROM
Your query would be
SELECT * FROM user WHERE...
Use mysql_num_rows() to check number of rows return from your query instead mysql_fetch_row
mysql is deprecated instead use mysqli or PDO
You need to start session at the top of your page
session_start();
Don't store plain password into database use password hashing technique
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/faq.passwords.php
Your code is open for sql injection read
How can I prevent SQL injection in PHP?
Your whole code would be
<?php
session_start();
//Establishing Connection with Server
$connection = mysql_connect("localhost", "root", "");
//Selecting Database from Server
$db = mysql_select_db("tanni", $connection);
if (isset($_POST['submit'])) {
//Fetching variables of the form which travels in URL
$mail = $_POST['mail'];
$pass = $_POST['pass'];
if ($mail != '' && $pass != '') {
$query = mysql_query("SELECT * FROM user WHERE mail='" . $mail . "' and pass='" . $pass . "'") or die(mysql_error());
$res = mysql_num_rows_row($query);
if ($res == 1) {
$_SESSION['mail'] = $mail;
} else {
echo'You entered username or password is incorrect';
}
} else {
echo'Enter both username and password';
}
}
//Closing Connection with Server
mysql_close($connection);
?>

how to check whether old password entered is present or not in db

I m having a login page where user enters id and password.To reset the password i have to check whether the entered password is present or not whether it matches with the id i have entered.How to validate it.I m unable to validate it. If user enters any password it displays the record is updated. How to validate it. Here is the code
login.php
<label type="text" name="id" maxlength="50" size="20">ID</label><br />
<input type="text" name="id" placeholder="ID" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">Password</label><br />
<input type="password" name="uid" placeholder="ID" class="input" size="20"/><br /></div>
<span class="field">(* Required field)</span><br /><br />
<input type="submit" name="login1" value="LOGIN" class="button"><br /><br /><br /><br />
</form>
</div>
</body>
</html>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$id= $_POST['id'];
$uid= $_POST['uid'];
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);
if(mysql_num_rows($run)>0){
echo "<script>window.open('resetp.php','_self')</script>";
}
else {
echo "<script>alert('Login details are incorrect!')</script>";
}
}
?>
resetp.php
<label type="text" name="uid" maxlength="50" size="20">Old Password</label><br />
<input type="text" name="uid" placeholder="id" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
<input type="password" name="pass" placeholder="pass" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="cpas" maxlength="50" size="20">Confirm Password</label><br />
<input type="password" name="cpas" placeholder="" class="input" size="20"/><br /></div>
<div class="formItem">
<input type="submit" name="login1" value="RESET" class="formButton"><br /><br /><br /><br /></div>
</form>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "resume1";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$pass= $_POST['pass'];
$uid= $_POST['uid'];
$cpas=$_POST['cpas'];
$query = "Update `resume` SET uid='".$_POST['pass']."' where uid='".$_POST['uid']."'";
$run = mysql_query($query);
if($query)
{
echo "<script>alert('Record updated')</script>";
}
else
{
echo "<script>alert('no')</script>";
}
}
?>
How can i validated it
Try this:
This line
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
should be
<label type="text" name="pass" maxlength="50" size="20">New Password</label><br />
I guess couldn't understand your requirement.
Why don't you validate like you are doing in login.php
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);.................
the PHP script should be at the beginning, not at the end of the code. Begin with the <?php .... ?> and then follow the <HTML> ... </HTML> otherwise the result is returned even before the script is processed.
There are a lot of security issues with your code. You can try this.
<?php
require 'db.php';
$username = isset($_POST['username']) ? htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8') : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8') : '';
$error = array();
$error_found = 0;
if(isset($_POST['submit']) && ($_POST['submit'] == 'Reset'))
{
//check for errors.
//check if username field is empty.
if(empty($username))
{
$error[] = 'Please provide your user-name.';
}
//check if password field is empty.
if(empty($password))
{
$error[] = 'Please provide a password.';
}
//if errors exist, put errors found as true.
if(!empty($error))
{
$error_found = 1;
}
//else no errors are found.
else
{
//proceed to reset.
//connecting to database.
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect, check your connection parameters. ');
mysql_select_db(MYSQL_DB, $db) or die('Could not select database, check availability. ' . mysql_error($db));
//querying the database. Checking if user-name password combination exists.
$query = 'SELECT username FROM resume WHERE username = "' . mysql_real_escape_string($username, $db) .
'" AND password = PASSWORD("' . mysql_real_escape_string($password, $db) . '")';
$result = mysql_query($query, $db) or die(mysql_error($db));
//checking if result is true.
if(mysql_num_rows($result) > 0)
{
//the result is true and so you can now reset your password.
}
else
{
$error[] = 'The username password combination you provided does not exist.';
$error_found = 1;
}
}
}
//HTML
?>
<!DOCTYPE HTML>
<html>
<head><title> ... </title></head>
<body>
<!--Your html code here -->
<?php
//if errors are found, then errors are shown here.
if($error_found == 1)
{
echo '<fieldset><center>';
echo '<ul>';
foreach($error as $e)
{
echo '<li>' . $e . '</li>';
}
echo '</ul>';
echo '</center></fieldset>';
}
?>
<form action="nameOfThisScript.php" method="POST">
Username:<input id="username" type="text" name="username" required />
Password:<input id="password" type="password" name="password" required />
<button id="Reset" type="submit" name="submit" value="Reset">Reset</button>
</form>
</body>
</html>
create a script named db.php in the same folder as this script and put the code
<?php
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('MYSQL_DB', 'resume1');
?>
Hope this helps.

Login form PHP using PDO statements

I am creating a signup and login form. In signup form i am taking inputs from the users and storing those inputs in my database. I want when user input username and password in nss-login.php then it compares from the database whether that username and password is available in database or not. If credentials are available then it redirects to nss-admin.php.
However, current code doesn't seem to be working for whatever, everything seems okay logically. I am fairly new to php about two weeks so obviously I'm missing something. I've been looking around to see what I am doing wrong but still can't figure it out, so I am posting here as a last resort. I appreciate you taking the time to view my question.
Please make the required changes in code files and rectify errors where necessary.
This is nss-functions.php
<?php
include 'nss-config.php';
function connect($config) {
try {
$conn = new PDO('mysql:host=localhost; dbname='.$config['database'],
$config['username'],$config['password']);
$conn -> setAttribute(PDO :: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
return $conn;
}
catch (Exception $e) {
return false;
}
}
function query($query,$bindings,$conn)
{
$stmnt = $conn->prepare($query);
$stmnt->execute($bindings);
return ($stmnt->rowCount() > 0) ? $stmnt : false;
}
?>
This is nss-signup.php
<!doctype html>
<html>
<head>
<title>Create a Free Account</title>
</head>
<body>
<?php
include 'nss-functions.php';
$conn=connect($config);
if (!$conn) die('Problem connecting to db.');
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repass = $_POST['repass'];
if(empty($username) || empty($email) || empty($password) || empty($repass)) {
echo "Please fill all inputs correctly";
}
else {
if($repass == $password) {
query("insert into users(username,email,password) values(:username, :email , :password)",
array('username' => $username, 'email' => $email , 'password' => $password) , $conn);
echo "Your account is successfully created";
}
else {
echo "Fill password correctly";
}
}
}
?>
<form action="nss-signup.php" method="post">
<h1>Create Your Account</h1>
<p><label for="username">Username</label>
<input type="text" id="username" name="username" /></p>
<p><label for="email">Email Address</label>
<input type="text" id="email" name="email" /></p>
<p><label for="password">Choose a Password</label>
<input type="password" id="password" name="password" /></p>
<p><label for="repass">Confirm Password</label>
<input type="password" id="repass" name="repass" /></p>
<p><input type="submit" value="Submit" name="loginform" /></p>
</form>
</body>
</html>
This is nss-login.php
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include 'nss-validate.php';
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$user = $_POST['username'];
$pass = $_POST['password'];
if(validate($user,$pass)) {
$_SESSION['user'] = $user;
header("Location:nss-admin.php");
}
else {
echo "Incorrect credentials";
}
}
?>
<form action="nss-login.php" method="post">
<h1>Sign in to Your Account</h1>
<p><label for="username">Username</label>
<input type="text" id="username" name="username" /></p>
<p><label for="password">Your Password</label>
<input type="password" id="password" name="password" /></p>
<p><input type="submit" value="Submit" name="loginform" /></p>
<p>Don't have an account? Create one.</p>
</form>
</body>
</html>
This is nss-validate.php
<?php
include 'nss-functions.php';
function validate($username,$password) {
$x = query("select username from users where username = :username", // variable for username
array('username' => $username) , $conn);
$y = query("select password from users where password = :password", // variable for password
array('password' => $password) , $conn);
return ($username == $x && $password == $y);
}
?>
This is nss-admin.php
<?php require 'nss-login.php'; ?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Hello, <?= $_SESSION['user']; ?></h1>
<h3>logout</h3>
</body>
</html>
$conn does not exist in the variable scope of your validate() function.
Change your function definition to this:
function validate($username,$password, $conn) {
and call it accordingly.
Note: Your validate function is completly useless. It will log everybody in with an existing password of any other user (if works at all, what I doubt). Also, you seem to store the password in plain text in the database.

mysqli_real_escape_string() expects parameter 1 to be mysqli

Here is my complete code....
Connect.php
$connect = #mysql_connect ($host, $username, $password, $db_name) or die ('error');
$select = #mysql_select_db($db_name, $connect) or die('check');
password .php
//forgot password update
include('C:\wamp\www\header.html');
//check if form has been submitted
include('C:\wamp\www\connect.php');
//connecting to db
$errors = array();
if(isset($_POST['submitted'])) {
if (empty($_POST['username']))
{
$errors[]='Please enter a username.';
}
else
{
$u = mysqli_real_escape_string($connect,trim($_POST['username']));
}
//check for current password
if (empty($_POST['password']))
{
$errors[]='Current password does not match.';
}
else
{
$p = mysqli_real_escape_string($connect,trim($_POST['password']));
}
//check for a new password and match with confirm pass.
if(!empty($_POST['password1']))
{
if($_POST['password1'] != $_POST['cpass'])
{
$errors[] = 'The entered password and confirm password do not match.';
}
else
{
$np = mysqli_real_escape_string($connect,trim($_POST['password1']));
}
}
if(empty($errors)){
//if everything is fine.
//verify the entered email address and password.
$q="SELECT username FROM users WHERE (username='$u' AND password=SHA1('$p'))";
$r=#mysqli_query($connect,$q);
$num = #mysqli_num_rows($r);
if($num==1)
//if it matches.
//get user id
{
$row=mysqli_fetch_array($r, MYSQLI_NUM);
//udpdate query.
$q="UPDATE users SET password= SHA1('$np') WHERE username=$row[0]";
$r=#mysqli_query($connect, $q);
if (mysqli_affected_rows($connect) ==1)
{
echo '<h3>Your password has been updated.</h3>';
}
else {
echo '<h3>Whops! Your password cannot be changed due a system error. Try again later. Sorry</h3>';
echo '<p>' .mysqli_error($connect). 'Query:' . $q.'</p>';
}
exit();
}
else
{
//invalid email and password
echo 'The entered username and password do not match.';
}
}
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
mysqli_close($connect);
}
?>
<html>
<head></head>
<body>
<div id="container">
<h1>Change your password</h1>
<form action="password.php" method="post">
Username:<br>
<input type="text" name="username" size="20" maxlength="80" />
<br>
Current Password<br/>
<input type="password" name="password" />
<br/>
New Password<br/>
<input type="password" name="password1" />
<br/>
Confirm New Password<br/>
<input type="password" name="cpass" />
<br/>
<input type="submit" name="submit" value="Change Password"/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>
<?php
include('C:\wamp\www\footer.html');
?>
http://www.php.net/manual/en/mysqli.real-escape-string.php
mysqli_real_escape_string
Parameters
link
Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()
escapestr
The string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
The first parameter must be a link identifier and not a string containing the DB name as it seems to be.
first parameter must be a link identifier, a value returned by http://www.php.net/manual/en/function.mysqli-connect.php or http://www.php.net/manual/en/mysqli.init.php
Blockquote

Categories