EDIT: The code now works. Added some code to the initial source code below.
So I have a database named payload and in it there's two tables; one named users and the other named tohere. Both of these tables just have two columns; userName and password. The tohere table is empty. The users table, however, has two populated rows. First row has admin and admin123 as the userName and password respectively. The second row has visitor and visitor123 as the userName and password respectively. There's a HTML form with two input fields where users enter a username and password. Now the idea is, if the username and password they enter in the form matches the records in the users table, I want those contents submitted to the tohere table which is currently empty. How do I accomplish that?
I have tried the following code which doesn't seem to work;
<html>
<head>
<title>
</title>
<?php
$message = "";
$theusername = $_POST['userName'];
$thepass = $_POST['password'];
if (count($_POST) >
0) {
$conn = mysqli_connect("localhost", "root", "", "payload");
$result = mysqli_query($conn, "SELECT * FROM users WHERE userName='" . $_POST["userName"] . "' and password = '" . $_POST["password"] . "'");
$count = mysqli_num_rows($result);
if ($count == 0) {
$message = "Invalid Username or Password!";
} else {
$sqltwo = "INSERT INTO tohere (userName, password) VALUES ('$theusername', '$thepass')";
//The below if statement was missing.
if(!mysqli_query($conn, $sqltwo)){
echo "Failed!";
}
else{
echo "Success!";
}
}
}
?>
</head>
<body>
<form action="" method="post" name="frmUser">
<div class="message">
<?php if ($message != "") {echo $message;}?>
</div>
<table align="center" border="0" cellpadding="10" cellspacing="1" class="tblLogin" width="500">
<tr class="tableheader">
<td align="center" colspan="2">
Enter Login Details
</td>
</tr>
<tr class="tablerow">
<td>
<input class="login-input" name="userName" placeholder="User Name" type="text"/>
</td>
</tr>
<tr class="tablerow">
<td>
<input class="login-input" name="password" placeholder="Password" type="password"/>
</td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2">
<input class="btnSubmit" name="submit" type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
So far, this code works, but only partially. When I enter username and password not in the users table, I get the message "Invalid Username or Password!", which is fine, but when I enter records that are in the users table, the form does not get submitted to the tohere table. In fact, nothing happens. Just a blank white screen. What gives?
Related
<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM telecomt_user WHERE email='$email'");
$row = mysql_fetch_array($res);
if ($row['password'] == md5($upass)) {
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
This is my code for fetching data from database to let the user to log in by email and password. My table name is "telecomt_user".
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required /> </td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>Sign Up Here</td>
</tr>
</table>
</form>
And this my html form code. The code works fine in localhost but when I uploaded it to my server it does not work. It always executes this line:
<script>alert('wrong details');</script>
Is it problem in my database? But I am using the same name and pattern what I used in my localhost and also my sign up form works with the same database. My "dbconnect.php" file is also okay. What is the problem?
instead of $row['password'] , can you try to type the column of the password in the string, for example $row[0] (if password column is the first column).
I think you have to put break point in each condition like
if(your condition){
echo "something";exit;
}else{
echo "nothing";exit;
}
Better to do checking on query only email and password
$res=mysql_query("SELECT * FROM telecomt_user WHERE email='$email' AND password='md5($upass)'");
$row=mysql_fetch_array($res);
Now condition login or not
if(count($row)>=1){
//login
}else{
// credentials wrong message
}
So basically, I'm trying to make a simple, yet secure, forgotten password script.
There are two scripts, one that allows the user to enter their email address. This will then send them an email with a link that they must visit to save their new password.
The second script is where the link leads to. This script saves the new password.
For security purposes, I made a new table within my database called 'token'. It has three fields; token, email, used. Token is a random generated string of 10 letters and numbers, email is just that users email address, and used is an integer of either 1 or 0 indicating whether or not the token has been used.
You will be able to understand far more of my structure once you read over the two scripts. They are not to long, and not complex at all.
What is going wrong
Okay, so there is only one small thing going wrong, and this is within the reset-password.php script. This is where the users come to after they receive the email. Basically, I type in a new password, and click 'Reset Password', yet nothing happens. No errors or confirmations are shown, along with nothing changing within my database. I can't seem to debug this, and have been searching and trying for hours now. All help and suggestions would be greatly appreciated.
Please try to keep in mind that I am still a newbie at PHP and MySQL. Been working with PHP for approximately 8 weeks now, and MySQL for only 2.
forgot-password.php
<?php
//Forgotten password script
//Variable to save errors
$errors = array();
$email = $_POST['email'];
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$query = "SELECT email FROM users WHERE email='" . $email . "'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num==0)
{
echo ("<div style='color:red;'>Email address is not registered</div>");
die();
}
$token = getRandomString(10);
$query = "INSERT INTO tokens (token,email) VALUES ('".$token."','".$email."')";
mysql_query($query);
//function to renerate the token
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++)
{
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
//Send the reset link to the user
function mailresetlink($to,$token)
{
$subject = "Password Reset";
$message = '
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Password Reset <noreply#domain.com>' . "\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "We have sent the password reset link to your email at <strong>".$to."</strong>";
}
}
//If email is posted, send the email
if(isset($_POST['email']))
{
mailresetlink($email,$token);
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>Email Address: </td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Reset My Password" /></td></tr>
<input type="hidden" name="register" value="TRUE" />
</form>
</table>
reset-password.php
<?php
//Reset password script
$token = $_GET['token'];
$email;
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(!isset($_POST['newpassword']))
{
$query = "SELECT email FROM tokens WHERE token='" . $token . "' AND used = 0";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$email = $row['email'];
}
if ($email != '')
{
$_SESSION['email'] = $email;
}
else
{
echo "Invalid link or Password already changed";
}
}
$pass = $_POST['newpassword'];
$email = $_SESSION['email'];
//Save new password
if(isset($_POST['newpassword']) && isset($_SESSION['email']))
{
$query = "UPDATE users SET password = SHA('$password') WHERE email='" . $email . "'";
$result = mysql_query($query);
if($result)
{
mysql_query("UPDATE tokens SET used=1 WHERE token='" . $token . "'");
}
echo "Your password has been changed successfully";
if(!$result)
{
echo "An error occurred. Please try the again or contact us at admin#domain.com";
}
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
Please, if you need any more information or code, please do not hesitate to ask.
Thanks in advance!
I don't see anywhere where you are passing the token parameter to the server on the reset page after entering the new password parameter. You should have another hidden <input /> control, I would expect. $_SERVER['PHP_SELF'] does not return query string parameters. That is likely the cause of your current problem.
Specifically,
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
should be
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
<input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
</form>
</table>
Make sure you also change any $_GET['token']s to $_REQUEST['token'] as it will be GET the first time, then POST the second.
That being said, your much larger problem is the ability for me to bypass all your security by specifying ' or 1=1 or ' as my token. Or, I could be mean and do a nice '; update users set password = SHA('IKnowThisPassword') where username = 'admin'; --
Moral of the story being parameterized SQL (How can I prevent SQL injection in PHP?)
I am making a web with a login system which is working fine.
I have also made a page which one has to log in to view. It is also working fine and when a user logs in it also gives a welcome "username" message.
However for an unknown reason this session variable is not being stored to the other pages. The thing is that I used the same methods which I used for the page with login restrictions.
Below is my login page. (works fine).
<?php
session_start();
?>
<form id="login_form" method="post" action="">
<p>
<?php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$password = $_POST["password"];
if(strlen($username) < 4 || strlen($password) < 4){
echo "Username or Password are invalid.";
}else{
require("connect.php");
$login = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password' ") or die(mysql_error());
if(mysql_num_rows($login) == 0){
echo "Username or Password are incorrect!";
} else{
require("member.php");
$member_info = mysql_fetch_assoc($login);
setMember($member_info["id"]);
$_SESSION['user'] = "$username";
echo "Welcome ".$member_info["fname"]." ".$member_info["lname"]."<br />";
echo "Redirecting... Please wait.";
jumpTo("my_logs_testing.php",2);
}
//Free result & close connection.
mysql_free_result($login);
mysql_close($link);
}
}else{
}
?>
</p>
<table frame="box" bgcolor="" width="40%" border="0" cellpadding="6" align="center">
<tr>
<td colspan="2"><div align="center"><font color="#FFFFFF"><strong>Diving Advisor | Log In System</strong></font> </div> </tr>
<tr>
<td width="25%"><font color="#FFFFFF"><strong><label for="username2">Username:</label></strong></font></td>
<td width="75%" align="left"><input name="username" type="text" id="username" size="30" maxlength="20" /></td>
</tr>
<tr>
<td><font color="#FFFFFF"><label for="password"><strong>Password:</label></strong></font></td>
<td align="left"><input name="password" type="password" id="password" size="30" maxlength="20" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit_login" id="submit_login" value="Log In" /></td>
</tr>
</table>
</form>
This is the page with login restriction (works fine).
<?php
session_start();
$current_user = $_SESSION['user'];
require("member.php");
if( !isMember() ){
header("Location: login.php");
} else {
?>
<?php
if(mysql_connect('localhost', 'root','') && mysql_select_db('diving_advisor')){
echo "Welcome ".$current_user;
$errors = array();
if(isset($_POST['datepicker'],$_POST['location'],$_POST['description'])) {
cont.......................
And this is one of the the other pages which is not working (session variable seems to be lost! HERE IS THE PROBLEM!!!!
<?php
session_start();
$current_user = $_SESSION['user'];
require("member.php");
?>
Here is code from template.......................
Then the editable region....
<?php
echo $current_user;
?>
<p><strong>Heading 1</strong></p>
<p>This is the home page of the diving advisor application.
Lore......
echo $currentuser is printing nothing on the page. It is suppose to print the logged in user but for some reason it is not.
Please help cause i really do not know what is wrong!!
Tks in advance.
session_start();
Needs to be the first thing that is called on each page.
While running the below script it shows the errorError: Unknown column 'email' in 'field list'.
<?php
include("connect.php");
if($loggedin == '1')
die("You can't register another account while you're logged in.");
if(isset($_POST['submit']))
{
$uname = trim($_POST['username']);
if($_POST["regkey"]!="171717")
die("Invalid Registration Key. <br> <a href= register.php>Back</a>");
if($_POST["pass"]!=$_POST["pass2"])
die("Passwords do not match. <br> <a href= register.php>Back</a>");
// Make sure all forms were filled out.
if((!isset($_POST['username'])) || (!isset($_POST['pass']))
|| ($uname == '') || ($_POST['pass'] == ''))
die("Please fill out the form completely. <br><br>
<a href=register.php>Continue</a>");
$check = #mysql_query("SELECT id FROM players WHERE username = '$uname'");
$check = #mysql_num_rows($check);
if($check > 0)
die("Sorry, that username has already been taken. Please try again.
<br><br>
<a href=register.php>Continue</a>");
$pass = md5($_POST['pass']);
$date = date("m/d/y");
$newPlayer = #mysql_query("INSERT INTO players (username, password,
registered,callname,email) VALUES ('$uname','$pass','$date','$_POST
[callname]','$_POST[email]')") or die("Error: ".mysql_error());
echo 'You have been registered! You may now <a href=index.php>Log in</a>.';
}
else
{
// A simple example of a form.
echo '
<center>
<form action=register.php method=post>
<p>Registration is currently<b> NOT OPEN.</b><br>
You must have a valid Registration key to register.</p>
<table border="2">
<tr>
<td>Username:</td><td><input type="text" name="username" size="20px"</input>
</td>
</tr>
<tr>
<td>Callname:</td><td><input type="text" name="callname" size="20px"</input>
</td>
</tr>
<tr>
<td>Password:</td><td><input type="password" name="pass" size="20px"</input>
</td>
</tr>
<tr>
<td>Re-type Password:</td><td><input type="password" name="pass2" size="20px"</input>
</td> </tr>
<tr>
<td>Email:</td><td><input type="text" name="email" size="20px"</input></td>
</tr>
<tr><td>Registration Key:</td><td><input type="text" name="regkey" size="20px"></input>
</td> </tr>
</table>
<input type="submit" name="submit" value="Submit"></input>
</form>';
}
?>
I'm very new to PHP and can't figure out why I'm getting this Error. Shouldn't the $_POST get that value from the form?
Thanks for reading.
It means your players table does not contain an email column. You will need to add this column to your table for this script to work.
So the incorrect part in your code is
$newPlayer = #mysql_query("INSERT INTO players(username, password, registered, callname, email)
VALUES('$uname', '$pass', '$date', '$_POST[callname]', '$_POST[email]')") or die("Error: ".mysql_error());
Add an email field in your player table.
Chances are there you misspelled email in the player.
$sql = "INSERT INTO user_registration (u_name,s_father,s_schoolname,s_rollno,s_class)
VALUES ($name,$father,$school,$rollno,$class)";
Error: INSERT INTO user_registration
(u_name,s_father,s_schoolname,s_rollno,s_class) VALUES (Azhar, hassan,
Chulli_payaan,1008,10th) Unknown column 'Azhar' in 'field list'
I have link change password in my home page..NOw i am telling you what i am doing...
First of all i creating a html form named edit_profile.php in which i have three textboxes old password,new password,confirm password.I have attcahed this page as a link to home page for changing password.
Next page i have designed named edit_profile1.php in which i am comaparing if new password and confirm passwords are equal or not
Then i making a query to search data with password = old password
But this page is not working.Now i am giving you the code both files and in last i will tell you what type error i am facing..
edit_profile.php
<?php
session_start();
?>
<html>
<body bgcolor="pink">
<table cellpadding="10" cellspacing="6" align="center" width="500">
<form name="form" action="edit_profile1.php" method="POST" >
<tr>
<td><b><i>Your Username</i></b></td>
<td><input type="text" name="username" id="username" size="30" maxlength="30" value="<?php echo $_SESSION['employee']['username']; ?>" disabled="disabled"></td>
</tr>
<tr>
<td><b><i>Old Password</i></b></td>
<td><input type="password" name="opassword" id="opassword" size="30" maxlength="30" value="" ></td>
</tr>
<tr>
<td><b><i>New Password</i></b></td>
<td><input type="password" name="npassword" id="npassword" size="30" maxlength="30" value="" ></td>
</tr>
<tr>
<td><b><i>Confirm Password</i></b></td>
<td><input type="password" name="cpassword" id="cpassword" size="30" maxlength="30" value="" ></td>
</tr>
<tr>
<td align="center" colspan="100"> <input type="submit" name="submit" value="Change Password"></td>
</tr>
</table>
</body>
</html>
Next Page
Next page is for edit_profile1.php
<?php
session_start();
if(isset($_POST['opassword']) && ($_POST['npassword']))
{
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could Not Connect:'.mysql_error());
}
mysql_select_db("tcs",$con);
$a=$_POST['opassword']; //old password value
$b=$_POST['npassword']; //new password value
$c=$_POST['cpassword'];
if ($b==$c) //checking if both new passowrd and c.password are equal or not
{
$pwd=hash('sha1',$b); //new value is assigned to pwd variable
$usr=$_SESSION['employee']['username']; //this varaible have value of username
$query="select * from employee where Username='{$usr}' and Password='{$a}'";
$result=mysql_query($query,$con);
$count = mysql_num_rows($result);
if ($count == 1)
{
$sql="update employee set Password='$pwd'";
$deepak=mysql_query($sql,$con);
if($deepak)
{
echo "Updation Successfull";
}
else
{
echo "Updation Not Possible.Some Error is there";
}
}
else
{
echo "There is some problem in macthing the old password with database password";
}
}
else
{
echo "Both Passwords are Not equal";
}
}
else
{
echo 'Error! Passwords were not sent!';
}
?>
<html>
<body bgcolor="orange">
<h4 style="position: relative;">Home Page</h4>
</body>
</html>
Error:
Every time i try to execute my programe the error is
Thhere is some problem in macthing the old password with database password
Now i am not getting where i am falling wrong.In database i have only one user row.Plz tell me what is error
Shouldn't
$query="select * from employee where Username='{$usr}' and Password='{$c}'";
be
$a = hash('sha1', $a); // added after conversation in comments
$query="select * from employee where Username='{$usr}' and Password='{$a}'";
instead? ($a instead of $c..)
Your script seems vulnerable to mysql-injection!
Apply mysql_real_escape_string to every value you insert in your SQL-Query!
It may be possible that your comparison doesn't work because there are extra spaces in the values your retrieve from the form. Try:
$a=trim($_POST['opassword']); //old password value
$b=trim($_POST['npassword']); //new password value
$c=trim($_POST['cpassword']);
Also:
if(isset($_POST['opassword']) && ($_POST['npassword']))
will not work.
You have to use:
isset($_POST['opassword']) && isset($_POST['npassword'])