php: Form to change password and insert current password - javascript

I'm making a form at which if user wants to change their password, i made a code that could change password from database but I want to implement some function before changing password, current password would be asked so that they can change their password, But how to do it?
code to update database:
strong text
$result = mysqli_query($con,"SELECT * FROM admin");
if ($row = mysqli_fetch_array($result)) {
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
}
echo "<h2>Your password is successfully changed..</h2>";
mysqli_close($con);
?>
here is a code for form:
<?php
include('lock.php');
?>
<form method="post" action="db_change_password.php">
<label><strong>Current password: </strong></label>
<input type="password" name="current_password" value="password"><br><br>
<label><strong>New password: </strong></label>
<input type="password" name="password" value="password"><br><br>
<label><strong>Confirm password: </strong></label>
<input type="password" name="confirm_password" value="password"><br><br>
<input type="submit" value="Submit">
<label><p><strong><br>NOTE: </strong>After changing password, you have to put your new password during login time.</p></label>
</form>
EDITING
login script:
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemail=mysql_real_escape_string($_POST['email']);
$mypassword=mysql_real_escape_string($_POST['password']);
$sql="SELECT * FROM admin WHERE email='$myemail' AND password='".sha1($mypassword)."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myemail and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION["myemail"];
$_SESSION['login_user']=$myemail;
header("location: home.php");
}
else
{
header("location: invalid_login_form.php");
}
}
?>

I would however make a session with the user_id
$result = mysqli_query($con,"SELECT * FROM admin WHERE email = '".$_SESSION['email']."'");
if ($row = mysqli_fetch_array($result)) {
if(sha1($_POST['current_password']) == $row['password'])
{
$id=$row['id'];
mysqli_query($con,"update admin set password=SHA1( CONCAT('Rajendra')) WHERE id='$id'");
} else {
echo "incorrect password";
}
}

Just before updating the password, you can add a check to test the current password.

Related

PHP login and set cookie properly

I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.

How can we give email id already exist using php mysql?

Code
<?php
mysql_connect('localhost','root','123456') or die(mysql_error());
mysql_select_db('email') or die(mysql_error());
?>
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$sql=mysql_query("insert into user(name,email)value('$name','$email')");
if($sql)
{
echo '<script>alert("successfull");</script>';
}
else
{
echo '<script>alert("error");</script>';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="" name="form">
<input type="text" name="name" id="name" placeholder="name">
<input type="text" name="email" id="email" placeholder="email">
<input type="submit" name="submit" id="submit">
</form>
</body>
how can we insert data into database without duplicate email id after submit it show alert msg that email id already exist?
thank you
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$query = mysql_query("select * from user where email = '$email'");
$result = mysqli_fetch_assoc($query);
if($result > 0 )
{
echo 'Email already exits';
}
else
{
// code here for insert or what ever you wants
}
}
?>
Firstly the mysql_* functions has been deprecated as of PHP version 5.5.0 and above. So its greatly advised to use mysqli_* functions.
To answer your question, a simple select query along with if statements would do:
$sql="SELECT * FROM users WHERE email = '$email'";
$result = $conn->query($sql);
if($result->num_rows>0){
//Email Already Exists
}
else
{
//Perform Insertion
}
Lastly, its highly recommended to use prepared statements.
First make a select query to check whether on this email and name entry already exist or not.
$SelectSqlQry=mysql_query("select COUNT(email) from user where email = '.$email.'");
$LengthRecords = mysqli_fetch_assoc($SelectSqlQry);
if($LengthRecords > 0) {
//do your alert or anything.
//alert email already exists.
echo '<script>alert("Email Already Exists");</script>';
}
else {
//Insert email..
}
then check your condition on this variable. SelectSqlQry

Php throwing sqli count errors

<? php
include_once("connection.php");
// email and password sent from form
$email = $_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$sql = "SELECT * FROM users WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($connection, $result);
// If result matched $username and $password, table row must be 1 row
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
}
?>
<div id="openModal" class="modalDialog">
<div>
X
<form class="pop" method="post" action="login.php">
<p class="login">LOGIN</p>
<div class="form-group">
<div class="left-inner-addon "><i class="fa fa-envelope-o fa-fw"></i>
<input type="email" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<div class="left-inner-addon"><i class="fa fa-key fa-fw"></i>
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
</div>
</div>
<p>Forgot Password?</p>
<div class="form-group">
<button class="btn btn-default" role="button" name="login" id="login">LOGIN</button>
</div>
</form>
</div>
</div>
<? php
$host = 'localhost';
$user = 'root';
$password = '';
$db = 'members';
$connection = mysqli_connect($host, $user, $password, $db);
if ($connection) {
echo "Connected Successfully";
} else {
echo "Error connecting: . mysqli_connect_error()";
}
?>
I have index.php, connection.php and login.php files. I have already created register.php for sign up it's working fine. In login.php, it is connected successfully but throwing an error in Warning: mysqli_num_rows() expects exactly 1 parameter, 2 given
One more thing I want to figure out how do I know if the users is login in my website I means I want to find out if it is stored to the database or I don't know as I'm new to SQL and after login there should valid or invalid email and password but not showing. In my database, I have created table the list of id, username, email, password. Please help in proper way and simple, don't confuse me.
The mysqli_num_rows() function returns the number of rows in a result set.
It accepts only one parameter say $result which is Required. $result is a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result(). You are passing the $connection object along with the $result which causes the issue.
For saving sessions in Database, reffer these posts
Storing Sessions in a Database
or
Saving PHP's Session data to a database
config.php
< ?php
$mysql_hostname = "hostname";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
Login.php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myemailid=addslashes($_POST['emailid']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$myemailid' and passcode='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
Session -> variables hold information about one single user, and are available to all pages in one application
if($count==1)
{
session_register("myusername");
$_SESSION['login_user']=$myusername;
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
Logout.php
< ?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>

PHP / Mysql : Register isn't creating new users in database

So I have two PHP files that are supposed to talk to eachother during User Registration.
The first: register.inc.php is supposed to create a new user in mysql database on MAMP and the second is register.php which is the basic form and is supposed to send it's data to register.inc.php. I am not receiving any errors in either files but it does not want to both: create the user and redirect to the register-success.php page.
Any idea what is going on?
register.inc.php:
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
//echo var_dump($_POST['username']);
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
// Sanitize and validate the data passed in
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
// Username validity and password validity have been checked client side.
// This should should be adequate as nobody gains any advantage from
// breaking these rules.
//
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error Line 39</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error">A user with this username already exists</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error line 55</p>';
$stmt->close();
}
// TODO:
// We'll also have to account for the situation where the user doesn't have
// rights to do registration, by checking what type of user is attempting to
// perform the operation.
if (empty($error_msg)) {
// Create a random salt
//$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); // Did not work
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password
$password = hash('sha512', $password . $random_salt);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./register_success.php');
}
}
register.php:
<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login: Registration Form</title>
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
<link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
<h1>Register with us</h1>
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
?>
<ul>
<li>Usernames may contain only digits, upper and lower case letters and underscores</li>
<li>Emails must have a valid email format</li>
<li>Passwords must be at least 6 characters long</li>
<li>Passwords must contain
<ul>
<li>At least one upper case letter (A..Z)</li>
<li>At least one lower case letter (a..z)</li>
<li>At least one number (0..9)</li>
</ul>
</li>
<li>Your password and confirmation must match exactly</li>
</ul>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>"
method="post"
name="registration_form">
Username: <input type='text'
name='username'
id='username' /><br>
Email: <input type="text" name="email" id="email" /><br>
Password: <input type="password"
name="password"
id="password"/><br>
Confirm password: <input type="password"
name="confirmpwd"
id="confirmpwd" /><br>
<input type="button"
value="Register"
onclick="return regformhash(this.form,
this.form.username,
this.form.email,
this.form.password,
this.form.confirmpwd);" />
</form>
<p>Return to the login page.</p>
</body>
</html>
You have this
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
But you do not have input in the form with name "p" -> $_POST['p']
so isset always return false
I suppose you wanted to type $_POST['password']
You just have to change the order of your db_connect and psl-config:
include_once 'psl-config.php';
include_once 'db_connect.php';

loging php page not redirecting

I'm working on a login page by user level to separate the admin and user. but it didnt seems to work. it doesnt redirect and leave a blank page. I've tried remove the javascript part, but it doesnt change anything either.
index.php
<form class="login" action="login.php" method="post">
Username:<input type="text" name="username" id="username"/>
Password:<input type="password" name="password" id="password"/>
<input type="submit" value="login"/>
</form>
login.php
<?php
session_start();
include('config.php');
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = mysql_query("SELECT * FROM admin WHERE username='$username' AND password='$password'");
$result = mysql_fetch_array($sql);
$username=$result['username'];
$adminID=$result['adminID'];
$userLevel=$result['UserLevel'];
$_SESSION['adminID']=$adminID;
$_SESSION['userLevel']=$userLevel;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if($userLevel == '1')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to Admin page! ");
</script>
<?php
header('Location:admin.php');
exit();
}
elseif($userLevel == '0')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to User page! ");
</script>
<?php
header('Location: user.php');
exit();
}
else
{
?>
<script type="text/javascript">
alert("Invalid Username or Password! ");
//window.location.href = "index.php";
</script>
<?php
}
}
?>
Use PHP Header:
for userLevel1:
header("Location: admin.php");
for userLevel2:
header("Location: user.php");
Name in your submit so it will enter your PHP code block:
<input type="submit" name="submit" value="login"/>
try the following code and replace into your code. see whether can work or not. you try on the first if condition first and see on the result. if cannot work tell me what problem you face.
<?php
if($userLevel == '1')
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script>
var a = alert("Welcome <?php echo "$username" ?> to Admin page! ");
if (a === true){
window.location.href="admin.php";
}
else{
window.location.href="admin.php";
}
</script>
<?php
}

Categories

Resources