I have been trying to create a reset password feature for my website, where the user can insert the already registered email and that will generate a random OTP and will be stored in the same column as the user's details such as
id firstname lastname username email resetpassword
1 name last user email OTP
this is my code but it's not working.
<?php
require 'dbh.php';
session_start();
$random = mt_rand(1000,1000000);
$email = $_POST['email'];
$sql = "SELECT Email FROM registeredusers WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
$emailCheck = mysqli_num_rows($result);
if (empty($email))
{
echo "please fill out all the fields";
}
else{
$result = mysqli_query($connection,$sql);
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
Header("Location: submitOTP.php");
}
?>
I am just trying this out so the form looks something like this
<form action="resetPassword.php" method="POST">
<input type="text" value="email" name="email"></input>
<input type="submit" value="submit"></input>
</form>
You should firts assigne the sql code and after execute the query
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
otherwise you simply repeat the previous (select ) query ..
and be careful for avoid sql injection take a look at prepared query and binding param
Related
I have this code:
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$query = mysqli_query($conn, "select name from accounts where name = '{$name}'");
if($query) {
echo "success";
} else {
echo "error";
}
}
?>
<form action="" method="post">
Name: <input type="text" name="name"><br><br>
<input type="submit" name="submit" value="Add">
</form>
And I have written this in the form and submitted, only return (error), and the table was not deleted.
For mysqli, multiple statements or multi queries must be executed with mysqli::multi_query()
So change
$query = mysqli_query($conn, "select name from accounts where name = '{$name}'");
to
$query = mysqli_multi_query($conn, "select name from accounts where name = '{$name}'");
then retry what you want in your own machine.
Of course, usually hacker will just gain privilege by logging as "admin" and then do whatever he/she wants (in that case just performing single query in a select statement thru a SQL attack will do and do not need to execute multi-queries)
[additional point]
For single query SQL attack, submit the following:
1}' or 1=1 or '{1=1
which will become:
select name from accounts where name='{1}' or 1=1 or '{1=1}'
or
1}' or name='admin' or '{1=1
which will become:
select name from accounts where name='{1}' or name='admin' or '{1=1}'
Hence, to avoid SQL attacks, please use parameterized prepared statements.
For details, you may refer to :
php mysqli prepared statements select
For example, if you will send like such request:
1';DROP table accounts where id!='123454321344321
For reason request encoding, you can use + sign instead of spaces.
I am writing an example with PHP simulate $name argument:
//That's a mean it is request variable
$name = "1';DROP table accounts where id!='123454321344321";
$query = mysqli_query($conn, "select name from accounts where name = '{$name}'");
if($query) {
echo "success";
} else {
echo "error";
}
Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>
I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement
I found this forum thread to make a log-in and registration system, but it doesn't check if password is correct, only username.
This is my log-in page code:
<?php
include('config.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$emailusername = mysqli_real_escape_string($obj->conn,$_POST['emailusername']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$password = md5($password);
$sql="SELECT uid FROM users WHERE username='$emailusername' or email = '$emailusername' and password='$password'";
$result=mysqli_query($obj->conn,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row['active'];
$count=mysqli_num_rows($result);
// If result matched $username and $username, table row must be 1 row
if($count==1)
{
$_SESSION['login_user'] = $emailusername;
header("location: index.php");
}
else
{
$error="<div style ='color:#c53131'>Your Login Name or Password is invalid</div>";
}
}
?>
</div>
<form class="fl" action="login.php" method="post">
<label>Username:</label><br/>
<input type="text" name="emailusername"/><br />
<br/>
<label>Password:</label><br/>
<input type="password" name="password"/>
<input type="submit" value=" Submit "/><br />
</form>
This is the table I use:
"uid INT(11) PRIMARY KEY AUTO_INCREMENT,".
"username VARCHAR(30) UNIQUE,".
"password VARCHAR(50),".
"name VARCHAR(100),".
"email VARCHAR(70) UNIQUE); ";
I am new to PHP and have no clue how to make it check if password is correct or incorrect. Any suggestions?
Try your query as below :
SELECT uid FROM users
WHERE (username='$emailusername' or email = '$emailusername')
and password='$password'";
CHECK YOUR Query
$sql="SELECT uid FROM users WHERE (username='$emailusername' OR email = '$emailusername') AND(password='$password')";
Please try the bellow query :
SELECT uid
FROM users
WHERE (username='$emailusername' OR email = '$emailusername')
AND password='$password'
Hope this will help you.
The query should be like this.
$sql="SELECT uid FROM users WHERE (username='".$emailusername."' or email = '".$emailusername."') and password='".$password."'";
If you have to use different logical operators, you should add brackets individual evaluation. Moreover, you have to pass username and password as strings.
I want to prevent if the user enters same email twice, which will create duplicate entry. Please help me to solve this small problem, I have searched stackoverflow for this problem but everyone has their own database with own method.
Thank you
<form action="create_subscriber.php" method="post">
<input placeholder="Name" name="inputName" type="name" required/>
<input name="inputEmail" placeholder="example#email.com" name="Submit" type="email" required/>
<input name="Submit" type="submit" value="Subscribe"/>
</form>
create_subscriber.php below
<?php
//include 'connection.php'
$dbhost = "localhost";
$dbuser = "sampleuser";
$dbpass = "samplepass";
$dbname = "sampledb";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
if(!$_POST['Submit']){
echo "Please enter a name & email";
//header('Location: index.php');
}else{
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES(NULL,'$name', '$email' ) ")
or die(mysql_error());
echo "User has been added";
header('Location: success.php');
}
?>
Since you are not doing any validation, you can use the Email as a unique field and do an REPLACE query. http://dev.mysql.com/doc/refman/5.0/en/replace.html
I would strongly advise you to write validation in the form of a query check against the database prior to attempting to do a secondary insert. It's even made easy by persistent connections being available so you don't have the overhead of few ticks it takes to do that validation query.
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES (NULL,'$name', '$email' )
WHERE NOT EXISTS (
SELECT email FROM subscriptions WHERE email='$email'
)")
Simply execute a preliminary query to check for email uniqueness
SELECT * FROM subscriptions WHERE `email` = ?
(I wrote the query in the form of a prepared statement
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You should use prepared statement to inject values into queries).
If you get any row then the email is not unique so redirect to the original form page, possibly displaying an error message.
If you don't get any record then you may proceed with the insert and then render a "mail registration succeeded" page.
Btw: you can't echo something and then set a header. As you start sending output header can't be set/changed.