Forgotpassword function not working, sql, php - php

Not sure what happened but its suddenly stopped working...
I can enter the email and username (i know the credentials are correct) and get the message that it wont find any matching details...
The content of forgotpassword.php:
<?php
require_once("users.inc");
$PAGE_TITLE = "Forgotten Password";
include $PHP_USERS_HEADER_FILE;
?>
<h3>Forgot Your Password?</h3>
<p>If you've forgotten your password, just enter the username and email address that you registered with, and your password will be emailed to you immediately.</p>
<form method="post" action="emailpassword.php">
<p><b>Your Username: </b>
<input type="text" name="username" size="35" />
</p><p>
<b>Your Email Address: </b>
<input type="text" name="email" size="35" />
</p>
<input type=submit value="Submit" />
</form>
the content of emailpassword.php:
<?php
require_once("users.inc");
$PAGE_TITLE = "Forgotten Password";
connect_to_users_db();
$password = fnRandomPassword(8);
$encrypt_pwd = md5($password);
$sql = "UPDATE users SET password='$encrypt_pwd' WHERE email='".$_REQUEST['email']."' AND username='".$_REQUEST['username']."'";
$query = mysql_query($sql);
$sql1 = "SELECT email, username, password FROM users WHERE email='".$_REQUEST['email']."' AND username='".$_REQUEST['username']."'";
$query1 = mysql_query($sql1);
if ($query1 && (mysql_num_rows($query1) > 0)) {
while (list($email,$username) = mysql_fetch_row($query1)) {
mail($email, "Your Password", "Below is the username and password information you requested.\n\nUsername: '$username'\nPassword: '$password'.\n\n","From: $WEB_MASTER <$WEB_MASTER_EMAIL>\n");
}
}
include $PHP_USERS_HEADER_FILE;
?>
<h3>Forgot Your Password?</h3>
<?
echo "<p>";
//if ($query && mysql_num_rows($query) > 0) {
if (mysql_affected_rows() > 0) {
?>
<p>We've emailed your password. You should receive it within a minute. If you don't, please send mail to the <?=$WEB_MASTER?>.</p>
<?php
} else {
?>
<p>We could not find an email and username corresponding with the email address and username you entered. Perhaps you registered with a different email address/username. Use the form below to try again.</p>
<form method="post" action="emailpassword.php">
<p><b>Your Username: </b>
<input type="text" name="username" size="35" />
</p><p>
<b>Your Email Address:</b>
<input type="text" name="email" size="35" />
</p>
<input type="submit" value="Submit" />
</form>
<p>If you believe you have not registered before, you are welcome to sign up now with the following form:</br>
<?php include 'fragments/requestaccont.htm';?>
<?php
}
?>
Is there some outdated coding here or something?

It stopt working because you changed the line which checks the query. Now it will e-mail a new password and displays the 'not found' message.
You are using mysql_affected_rows() but the last query was a SELECT query which doesn't effect rows. Change the line:
if (mysql_affected_rows() > 0) {
Into this line:
if ($query1 && (mysql_num_rows($query1) > 0)) {
Also listen to Doon, mysql_* is deprecated.

Related

Is anything wrong with this code?

I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code
Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-

Log in page not working even though POST variables being queried have a match in user database

I apologize for what will probably be a lengthy post.. I'm fairly new with PHP and trying to get a working registration / log in system for users on my website for a final project.
The log in system was working for registered users until I modified the way registration is validated. I need to have some angular on the website for the project requirements so I created a registration page that looks like this :
register.php
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" method="post" action= "<?php htmlentities($_SERVER['PHP_SELF'])?>" novalidate>
<p>Username:<br>
<input type="text" name="myusername" value="myusername" ng-model="myusername" required>
<span style="color:red" ng-show="myForm.myusername.$dirty">
<span ng-show="myForm.myusername.$error.required">Username is required.</span>
</span>
</p>
<p>Password:<br>
<input type="password" name="mypassword" value="mypassword" ng-model="mypassword" required>
<span style="color:red" ng-show="myForm.mypassword.$error.required && myForm.mypassword.$dirty">Password Required</span>
</p>
<p>Email:<br>
<input type="email" name="myemail" value="myemail" ng-model="myemail" required>
<span style="color:red" ng-show="myForm.myemail.$dirty && myForm.myemail.$invalid">
<span ng-show="myForm.myemail.$error.required">Email is required.</span>
<span ng-show="myForm.myemail.$error.myemail">Invalid email address.</span>
</span>
</p>
<p>
<input type="Submit" name="Submit" value="Submit" ng-disabled="myForm.myusername.$invalid || myForm.myemail.$invalid || myForm.mypassword.$invalid">
</p>
if (isset($_POST['Submit'])) { //form submission
$newusername = sanitize($_POST['myusername']); //sanitize username, email, and password
$newpassword = sanitize($_POST['mypassword']); // encrypt password
$newemail = sanitize($_POST['myemail']);
$sqlname = "SELECT username FROM users WHERE username = '".$newusername."'";
$result1 = $conn->query($sqlname);
if ($result1->num_rows > 0) //make sure username does not exist
{
echo "
<script>
alert('Username already taken. Try again.')
</script>
";
}
$sqlemail = "SELECT email FROM users WHERE email = '".$newemail."'"; //make sure email does not exist
$result2 = $conn->query($sqlemail);
if ($result2->num_rows > 0)
{
echo "
<script>
alert('That email is already in use.')
</script>
";
}
if (($result1->num_rows < 1) && ($result2->num_rows < 1)) //if no results for username or email query register user
{
$sqlinsert = "INSERT INTO users SET username = '".$newusername."', password = '".$newpassword."', email = '".$newemail."'";
$conn->query($sqlinsert);
echo "".$newusername." has registered. ";
}
};
?>
The registration is working just fine. If I register a user named 'testuser' with 'testpassword' it shows up in the user database.
The issue is now any accounts created with the angular registration are not able to log in. (Accounts created before adding the angular work fine)
The log in pages look like this:
Login.php
<form id='form1' name='form1' method='post' action='php/checklogin.php'>
<form role='form'>
<div class='form-group'>
<label for='username'>Username</label><input type='text' class='form-control' id='myusername' name='myusername'>
</div>
<div class='form-group'>
<label for='password'>Password</label><input type='password' class='form-control' id='mypassword' name='mypassword'>
</div>
<button type='submit' id='Submit' name='Submit' value='Submit' class='btn btn-default'>Submit</button>
</form>
checklogin.php
<?php
require("connect.php");
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$query = $conn-> prepare("SELECT * FROM users WHERE username ='".$myusername."' AND password='".$mypassword."'");
$query->execute();
$query->store_result();
$result = $query->num_rows;
if ($result < 1 ){
//header('Refresh: 2;url=..\login.php');
echo "<span style='color: red'>Wrong Username or Password. Try again.</span>";
var_dump($myusername, $mypassword);
}
else if ($result > 0) {
session_start();
$_SESSION['myusername']= $myusername;
header('Refresh: 0;url=..\index.php');
}
else {
echo "oops, there was an error";
}
?>
For some reason I am now getting invalid username / password for any account I create when I try to log in with it.
The var dump shows the variable values are being set - ie (user="testuser" password="testpassword") and the user is in the database however the query is failing.
Any help would be appreciated! Thank you!

PHP sessions to go to user specific page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to make a page where a user logs in and they are taken to a personalized page. What I am having problems with is, while the user is still logged in, if they type in the generic url, that they are still logged in and their personalized page is viewable. (Similar to when you are logged into Facebook and it goes straight to your feed if you type in www.facebook.com) I tried using sessions for this, but am having no luck.
<?php
if(isset($_REQUEST['user']) != true) {
?>
<html>
<head>
<title>Welcome</title>
</head>
</html>
<body bgcolor="white">
<h1>Welcome</h1><br>
If you have an existing account, log in here:<br>
<form name="loginForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /></br>
<input type="submit" value="Login" />
</form>
<br>
<hr>
<br>
Otherwise, if you'd like to create an account, please fill out the following form:<br>
<form name="createAccountForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /><br>
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="hidden" name="create" value="true">
<input type="submit" value="Create Account" />
</form>
</body>
</html>
<?php
}
else if(isset($_REQUEST['user']) == true) {
session_start();
if(!isset($_SESSION['uname']))
{
header('location:test.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
// personalized page code
}
EDIT:: A solution first for your own existing code. should work fine.
<?php
session_start();
if(isset($_REQUEST['user'])) {
if(isset($_SESSION['uname']))
{
header('location:test.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
// personalized page code
} else {
?>
<html>
<head>
<title>Welcome</title>
</head>
</html>
<body bgcolor="white">
<h1>Welcome</h1><br>
If you have an existing account, log in here:<br>
<form name="loginForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /></br>
<input type="submit" value="Login" />
</form>
<br>
<hr>
<br>
Otherwise, if you'd like to create an account, please fill out the following form:<br>
<form name="createAccountForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /><br>
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="hidden" name="create" value="true">
<input type="submit" value="Create Account" />
</form>
</body>
</html>
<?php
}
?>
Here is a login solution of my own (stripped out a bit to be generic) it also includes the code for a PDO query of the database and checking of a password with php's password_hash function. I will point out the code that is specifically relevant to your question:
Assuming that as you are building a login page, and wanting to send users to other parts of the site relevant to their status. I think the whole script is relevant. You can easily swap and change what happens as a result of the session variable values.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//start the session before sending any other output
session_start();
require('dbconn.php');
// checks if a session eid has been set, if so, send them to the usercp.
if(isset($_SESSION['eid'])){ header("Location: usercp.php"); } else {
try{
//build a login page
$loginpage ="<html><head><title>Portal Login</title></head><body>";
$loginpage.="<div align=\"center\" id=\"box\">";
$loginpage.="<table><tr><td><img src=\"images/login.jpg\" /></td></tr>";
$loginpage.="<tr><td><div align=\"center\">";
$loginpage.="<font face=\"Courier New, Courier, monospace\">Please enter your email<br /> address and password.</font><br />";
$loginpage.="<br /><form action=\"\" method=\"post\" name=\"login\" ><div align=\"right\">";
$loginpage.="<font face=\"Courier New, Courier, monospace\">Email:</font><input type=\"text\" size=\"40\" name=\"email\" />";
$loginpage.="<br /><br /><font face=\"Courier New, Courier, monospace\">Password:</font><input type=\"password\" size =\"40\" name=\"password\" />";
$loginpage.="<br /></div><br /><input type=\"reset\" value=\"Reset\" /> ";
$loginpage.=" <input name=\"submit\" type=\"submit\" value=\"Login!\" />";
$loginpage.="</form></div></td></tr></table></div></body></html>";
//checks if somebody is trying to login
if(isset($_POST['submit']))
//checks that the username and password have both been filled out if not, show the login page
{ if(!$_POST['email'] || !$_POST['password'])
{
echo $loginpage;
echo "Please enter your login details";
} else { //otherwise search the database for the email address
$db = NEW pdo($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$email = $_POST['email'];
$password = $_POST['password'];
$check = $db->prepare("SELECT * FROM employees WHERE email = :email");
$check->bindParam(":email", $email);
$check->execute();
//unset the session variables
unset($_SESSION['eid']);
unset($_SESSION['email']);
unset($_SESSION['userlevel']);
unset($_SESSION['fname']);
//check if the password hash matches php's hash of the password
if(($row = $check->fetch()) && (password_verify($password,$row['password']))) {
// set the session variables
$_SESSION['eid'] = $row['eid'];
$_SESSION['email'] = $row['email'];
$_SESSION['userlevel'] = $row['userlevel'];
$_SESSION['fname'] = $row['fname'];
// if the user's userlevel is higher than 1 give them the option of the admin page
if($row['userlevel'] > "1") {
echo "<center><a href='usercp.php'><h1>User Panel</h1></a><br><br><a href='admin/admincp.php'><h1>Admin Panel</h1></a></center>";
} else { //otherwise send them straight to the usercp
header("Location: usercp.php");
}
} else { //if the email is not found or password is incorrect, show the loginpage again
echo $loginpage;
echo "Login details incorrect, please contact your manager.";
}
}
} else { //if nobody has logged in already, or tried to log in just now, show the login page
echo $loginpage;
}
//pdo error reporting code
} catch (PDOException $e) {
throw $e;
}
}
?>

How can I messages between separate sections of one page?

Basically, in the following code:
<?php
$hostname = '';
$username = '';
$password = '';
$dbn = '';
try {
$dbh = mysqli_connect($hostname , $username, $password ,$dbn);
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if (isset($_POST['formsubmitted'])) {
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$email1 = $_POST['email1'];
$password1 = $_POST['password1'];
$dob = $_POST['dob'];
$query_verify_email = "SELECT * FROM User WHERE Email = '$email1'";
$result_verify_email = mysqli_query($dbh, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
//$id= uniqid();
$query_insert_user = "INSERT INTO `User` ( `Name`, `Username`, `Email`, `Password`, `DOB`, `Activation`) VALUES ( '$fullname', '$username', '$email1', '$password1', '$dob', '$activation')";
$result_insert_user = mysqli_query($dbh, $query_insert_user);
if (!$result_insert_user) {
echo 'Query did not work ';
}
if (mysqli_affected_rows($dbh) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= 'http://website' . '/active.php?email=' . urlencode($email1) . "&key=$activation";
mail($email1, 'Registration Confirmation', $message, 'From: a#b.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.
</div>';
}
mysqli_close($dbh);//Close the DB Connection
}// End of the main Submit conditional.
?>
<html>
<head>
</head>
<body>
<form name="f1" action="Main.php" method="post">
<p>Full name: <br/><input class="tb10" type="text" name="fullname" /></p>
<p>Username: <br/><input class="tb10" type="text" id="username" name="username" /><br/>
<p>Email: <br/><input class="tb10" type="text" id="email1" name="email1" /></p>
<p>Re-Enter Email: <br/><input class="tb10" type="text" name="email2" /></p> <br/>
<p>Password: <br/><input class="tb10" type="password" name="password1" /></p>
<p>Re-Enter Password: <br/><input class="tb10" type="password" name="password2" /></p><br/>
<p>Date of Birth: <br/><input class="tb10" type="text" name="dob" /></br><img src="img/calendar1.gif" alt="Calendar" onclick="displayCalendar(document.forms[0].dob,'yyyy/mm/dd',this)"/></p><br/>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Submit" class="button" />
</div>
</form>
</body>
</html>
The problem is I want to show the message that show up in the top (before the html part) in the body part. That means when the user completes the registration, the message will show up instead of the fields in the body section (Name, UserName, Email ,....).
To illustrate it:
If the registration is valid, I want the message:
Thank you for registering! A confirmation email has been sent to '.$email1.' Please click on the Activation Link to Activate your account
Appears in the body part (instead of the fields).
I hope you understand my explanation.
You set a variable, let it be regSuccess, in the php part to either true to false depending on whether user registration was successfull or not
Then in the html part, you checkk for the value of this variable in an if condition and output the corresponding html.
<?php
if($regSuccess == TRUE) {
?>
Thank you message
<?php
}
else
{ ?>
the input fields
<?php
} ?>
you could create a variable to store you error message instead of echo it directly.
And add a 'IF' case in the <body> for validation occur error, echo the error, otherwise print the register form.
Utilize a $_SESSION variable to indicate that the user successfully registered. You will start a session on your page and check if that value is set before doing anything else. If the variable exists, then display the activation message, otherwise provide the registration fields and continue with your existing code.
The reason for utilizing $_SESSION is to persist state information between page requests.
<?php
session_start();
if(isset($_SESSION['registered_email'])){
//Display message indicating user has already registered
echo 'Thank you for registering! A confirmation email has been sent to '. $_SESSION['registered_email'] .' Please click on the Activation Link to Activate your account';
}else{
// The rest of your code
...
// set session variable to indicate the registration was successful
$_SESSION['registered_email'] = $email1;
...
}
?>

PHP email subscription validation and check for existing

I am creating an email subscription form in PHP and want to check for a valid address as well as if the email is already existing in my database.
My code is connecting to my database and inserting but the validation as well as checking for an existing email are not working.
No matter what I type into my form it inserts it into my database even if I don't type anything.
Here is all of my code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Subscribe to Our Newsletter </legend>
<?php if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
$feedback='';
if (!$email) {
$feedback .= '<strong>Please enter your email address</strong><br />';
}
if (!$name) {
$feedback .= '<strong>Please enter your name</strong><br />';
}
list($username, $mailDomain) = explode("#", $email);
if (!#checkdnsrr($mailDomain, "MX")) {
$feedback .= '<strong>Invalid email domain</strong><br />';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)) {
$feedback .= '<strong>Your email address doesn\'t appear to be valid - please check and try again';
}
function cleaninput($value, $DB) {
if (get_magic_quotes_gpc()) {
$value = stripslashes( $value );
}
return mysql_real_escape_string( $value, $DB );
}
$name=$_POST['name'];
$email=$_POST['email'];
include_once "connect.php";
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
if ($insertresult) {
$completed = true;
}
if($competed=false) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post">
<fieldset>
<legend>Subscribe to OUr Newsletter </legend>
<?php
if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
}
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
?>
Also the last echo in my script is always there. It is displayed under my my form always. Not sure why that is. Maybe I have it in the wrong place in my code.
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
Thanks!
This code is a bit of a mess, to be honest :) It's slightly difficult to read, but I can see at least two problems: you write $competed rather than $completed in one of your if statements, and you don't actually have the INSERT query in an if block: it'll always execute. Try putting it in an else block after the if block that checks whether the address is already in your database, like this:
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
else {
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
}
You also don't need to use both addslashes and mysql_real_escape_string; just the latter will do. And I'm not sure why you have the same form in your code twice. Surely once should do? :)

Categories