Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}
Related
I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>
This question already has an answer here:
PHP's white screen of death [duplicate]
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Basically I have this form that asks for email and password.
What I want to do is to compare and check if the inputs match with the data from my table/database.
This is my registration.php (the form)
<form action="Authentication.php" method="post">
<b>Returning Intern Login</b><br/><br/>
Enter your e-mail address: <input type="text" name="email" /><br/><br/>
Enter your password: <input type="password" name="pw2"/><br/><i>(Passwords are case-sensitive and must be 6 characters long)</i><br/><br/>
<input type="reset" value="Reset Login Form" />
<input type="submit" name="submit2" value="Log In" /><hr/><br/>
</form>
and this is the Authentication.php
session_start();
$link = mysqli_connect('localhost','root','');
$database = mysqli_select_db($link,'internship');
$user = $_POST['email'];
$pass = $_POST['pw2'];
// User is logging in
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
It works with the empty inputs.
But when I gave an email and password exactly same from the database/table,
It displays white blank page..
You need to write the entire code within an if statement to ensure the field is filled in, like so:
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
/* Code */
}
if (empty ($pass)) //if password field is empty echo below statement
{
/* Code */
}
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
else
{
echo "Empty input submit2"; // empty $_POST["submit2"]
}
Hope this helps.
Mysqli takes 4 parameters hostname,username,password, and dbname:
<?php
session_start();
$link = mysqli_connect('localhost','root','','internship');
// User is logging in
if (isset($_POST["submit2"]))
{
$user = $_POST['email'];
$pass = $_POST['pw2'];
if (empty($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
else if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". $user ."' AND password = '".$pass."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
?>
I am working on a simple registration system and after hours of research am still stuck.
If my database is clear (I delete any rows in the table), and I submit the form, it sends a validation email and activates and allows me to login.
If I try to create another account with the same email, I am not getting my error message like I should be, telling the user "the email has already been registered." It just takes me to a blank page, even if I use a new email address after the first row has been created.
When I look at my table, the row created by the form (the first time) has the auto-inc ID which is right, the username is input into the row, but password, email, and activation all say '0'.
Can anyone see where the error is in my code? I need the code to verify that the email entered isn't already used, and if it is, to display the errormessage. If it isn't, it should be creating a new row in the table with the information.
I know I need to hash the password. I'm just trying to get the information in the table right before I proceed with security.
index.php
<?php
include 'sessions.php';
if(isset($_SESSION['errormessage'])){
echo ($_SESSION['errormessage']);
unset ($_SESSION['errormessage']);
}
?>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<form name="newForm" method="post" action="createaccount.php">UserName:
<input type="text" name="newUserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="newPass1" size="15">
<br>Confirm Password:
<input type="password" name="newPass2" size="15">
<br>Email:
<input type="email" name="newEmail" size="15">
<br>
<input type="submit" name="newSubmit">
<input type="reset" name="newReset">
</p>
</form>
<hr>
<form name="newForm" method="post" action="login.php">
<strong>Already Registered? Login Here:</strong>
<br>
UserName:
<input type="text" name="UserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="Pass1" size="15">
<br>
<input type=submit name=SubmitButton value=Submit>
<input type=reset name=ResetButton value=Clear>
</form>
</body>
</html>
createaccount.php
<?php
include ('sessions.php');
include ('database_connection.php');
//function to test password
function passwordStrength($pwd) {
//test for at least 8 characters
if (strlen($pwd) < 8) {
return false;
}
//test for max length
if (strlen($pwd) > 16) {
return false;
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
return false;
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
return false;
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
return false;
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
return false;
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
return false;
}
else {
return true;
}
return true;
}
if(isset($_POST['newSubmit'])){
if(empty($_POST['newUserName'])) {
$_SESSION['errormessage'] = "Please enter a username!";
header("Location: index.php");
}
else if (strlen($_POST['newUserName']) < 4) {
$_SESSION['errormessage'] = "Username is too short!";
header("Location: index.php");
} else if(strlen($_POST['newUserName']) > 16) {
$_SESSION['errormessage'] = "Username is too long!";
header("Location: index.php");
} else if(empty($_POST['newPass1'])) {
$_SESSION['errormessage'] = "You must enter a password!";
header("Location: index.php");
} else if(empty($_POST['newPass2'])) {
$_SESSION['errormessage'] = "You must confirm your password!";
header("Location: index.php");
} else if($_POST['newPass1'] !== $_POST['newPass2']) {
$_SESSION['errormessage'] = "Passwords do not match!";
header("Location: index.php");
} else if(!passwordStrength($_POST['newPass1'])) {
$_SESSION['errormessage'] = "Password does not meet requirements!";
header("Location: index.php");
} else if(empty($_POST['newEmail'])) {
$_SESSION['errormessage'] = "Must enter an email address!";
header("Location: index.php");
} else {
$Email = $_POST['newEmail'];
$name = $_POST['newUserName'];
$Password = $_POST['newPass1'];
//echo "All fields accepted!";
//$pwd = $_POST['newPass1'];
//echo hash("sha256", $pwd);
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
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));
$query_insert_user = "INSERT INTO `userDB` ( `username`, `email`, `password`, `activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($db, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($db) == 1) { //If the Insert Query was successfull.
//send the email
$to = $_POST['newEmail']; // this is your Email address
$from = "mtshort87#gmail.com"; // this is the sender's Email address
$subject = "Account Succesfully Created";
$message = "Thank you for creating an account. Please activate it now using the link below!";
$message2 = "http://cts.gruv.org/short/form/activate.php?username=".$_POST['newUserName']."\n";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message2,$message,$headers);
mail($from,$subject,$message2,$message,$headers); // sends a copy of the message to the sender
$_SESSION['errormessage'] = "A confirmation e-mail has been sent to you. Please activate your account to login.";
header("Location: index.php");
}
mysqli_close($db);//Close the DB Connection
}
}
}
activate.php
<?php
include 'sessions.php';
include 'database_connection.php';
if (isset($_GET['Email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_GET['Email']))
{
$email = $_GET['Email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))//The Activation key will always be 32 since it is MD5 Hash
{
$key = $_GET['key'];
}
if (isset($Email) && isset($key))
{
// Update the database to set the "activation" field to null
$query_activate_account = "UPDATE userDB SET activation=NULL WHERE(email ='$Email' AND activation='$key')LIMIT 1";
$result_activate_account = mysqli_query($db, $query_activate_account) ;
// Print a customized message:
if (mysqli_affected_rows($db) == 1)//if update query was successfull
{
echo '<div class="success">Your account is now active. You may now Log in</div>';
} else
{
echo '<div class="errormsgbox">Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
mysqli_close($db);
} else {
echo '<div class="errormsgbox">Error Occured .</div>';
}
?>
If any more information is requested I will edit this post.
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
http://php.net/manual/en/mysqli.query.php
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Since you are using a correct SQL select statement, mysqli_query will return a mysqli_result object.
There is a num_rows attribute in mysqli_result that indicates the number of rows found. You can use it to check if there is a record with that email.
Always use LIMIT 1 when you expect 1 result.
FIX:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email' LIMIT 1";
$result_verify_email = mysqli_query($mysqli, $query_verify_email);
if (is_object($result_verify_email) && $result_verify_email->num_rows > 0) {
echo "Email already exists";
}
Separately the forms are ok, but combined.... not really. The struggle is that i can't access the variable $name from the first if statement in the second.
Error : Undefined variable: name
html:
<form method="POST" enctype="multipart/form-data" id="form1">
Name: <input type="text" name="name"><br>
Pass: <input type="password" name="pass"><br>
<input type="submit" name="submit1" value="Влез">
</form>
<form method="POST" enctype="multipart/form-data" id="form2">
We need some more information about you<br>
Please enter your e-mail: <input type="text" name="email"><br>
Please enter a new Password <input type="password" name="pass1" ><br>
Plese reenter tour new password <input type="password" name="pass2"><br>
<input type="submit" name="submit2" value="Save">
</form>
php:
require('config.php');
?><script type="text/javascript">document.getElementById("form2").style.display="none"; </script><?php
if(isset($_POST['submit1']))
{
$name = mysql_escape_string($_POST['name']);
$pass = mysql_escape_string($_POST['pass']);
//chek if the username and password are correct
$check = mysql_query("SELECT * FROM test WHERE name = '$name' AND pass = '$pass'");
if(mysql_num_rows($check) >= 1)
{
?>
<script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="block";
</script>
<?php
exit();
}
else echo "<h1><font color='red'> Грешно Име или Парола</font></h1>";
}
if(isset($_POST['submit2']))
{
$email = mysql_escape_string($_POST['email']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$checkpass = mysql_query("SELECT * FROM test WHERE pass = '$pass1'")or die(mysql_error());
if($pass1 != $pass2){
echo "Passwords do not Match";
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Wrong email format";
}
elseif (mysql_num_rows($checkpass)>=1) {
echo "Password already taken";
}
elseif (empty($pass1) || empty($pass2) || empty($email)) {
echo "Not all fields are filled";
}
else
{
//put in DB
mysql_query("UPDATE test SET pass='$pass1' WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE test SET email='$email' WHERE name='$name'") or die(mysql_error());
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="none";
</script><?php
echo "<h1><font color='green'>Registration successful</font></h1>";
}
}
P.S don't mind the java script inside and no, i can't combine the forms!
The reason you cannot access the $name variable inside your second if statement is due to the form structure. You have two distinct forms and only one of them can be submitted at any time. Your if statements can therefore only handle one of the forms, either submit1or submit2. The simplest solution could be to combine the two forms and your if statements. You would then need more if statements to check what information has been provided and should be processed.
Bonus
One of your forms has names not in English. It is good practice to write code using the English language as other developers not familiar with your language are to read your code (as we do now). This also helps others if they want to research your implementations on the internet.
I would also recommend checking up on separation of concerns. As of now your code mixes presentation logic and domain logic (the action processing stuff). This may seem overwhelming, but I can assure you that it is an investment you will love in the future.
Happy coding!
As noted in the comments, you have an issue where only one function will be called, if you want the info from submit1 to be accessible in submit2, then change up your if statements.
if(isset($_POST['submit1']) || isset($_POST['submit1']))
{
//submit1 code here
if(isset($_POST['submit2']))
{
//submit2 code here
}
}
This way, submit1 data will run for both submit buttons, and submit2 will be able to make use of the data as needed.
i tried passing the variable with session_start() like this:
if(isset($_POST['submit1']))
{
$name = mysql_escape_string($_POST['name']);
session_start();
$_SESSION["a"] = $name;
$pass = mysql_escape_string($_POST['pass']);
//chek if the username and password are correct
$check = mysql_query("SELECT * FROM test WHERE name = '$name' AND pass = '$pass'");
if(mysql_num_rows($check) >= 1)
{
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="block";
</script><?php
}
else echo "<h1><font color='red'> Грешно Име или Парола</font></h1>";
}
if(isset($_POST['submit2']))
{
session_start();
$name = $_SESSION["a"];
$email = mysql_escape_string($_POST['email']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$checkpass = mysql_query("SELECT * FROM test WHERE pass = '$pass1'")or die(mysql_error());
if($pass1 != $pass2){
echo "Passwords do not Match";
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Wrong email format";
}
elseif (mysql_num_rows($checkpass)>=1) {
echo "Password already taken";
}
elseif (empty($pass1) || empty($pass2) || empty($email)) {
echo "Not all fields are filled";
}
else
{
//put in DB
mysql_query("UPDATE test SET pass='$pass1' WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE test SET email='$email' WHERE name='$name'") or die(mysql_error());
?><script type="text/javascript">
document.getElementById("form1").style.display="none";
document.getElementById("form2").style.display="none";
</script><?php
echo "<h1><font color='green'>Registration successful</font></h1>";
}
}
UPDATE(solved): Previously I set the password length to 15 characters where it should be 32 character since the password is encrypted to md5. Now it works fine. Thanks for all the answers and suggestions.
Below is the register php code. The code works fine and able to store password in the database in md5.
<html>
<?php
error_reporting(0);
if($_POST['submit'])
{
$name = mysql_real_escape_string($_POST['name']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password1 = mysql_real_escape_string($_POST['password1']);
$enc_password = md5($password);
if($name && $username && $password && $password1)
{
if(strlen($name)<30)
{
if(strlen($username)<10)
{
if(strlen($password)<15 || strlen($password)>6)
{
if($password == $password1)
{
require "dbc.php";
$query = mysql_query("INSERT INTO users VALUES ('$name','$username','$enc_password')");
echo "Registration Complete! <a href='index.php'>Click here to login</a>";
}
else
{
echo "Passwords must match";
}
}
else
{
echo "Your password must be between 6 and 15 characters";
}
}
else
{
echo "Your username is too long";
}
}
else
{
echo "Your name is too long";
}
}
else
{
echo "All fields are required";
}
}
?>
<form action="register.php" method="POST">
Name: <input type="text" name="name" value="<?php echo "$name"; ?>"> Max Length:30<p>
Username: <input type="text" name="username" value="<?php echo "$username"; ?>"> Max Length:10<p>
Password: <input type="password" name="password"> Max length:15<p>
Re-Enter Password: <input type="password" name="password1"><p>
<input type="submit" name="submit" value="Register">
</form>
<input type="button" value="<< Back to Login Area" onclick="window.location='../login%20and%20registration/members.php'">
</html>
Below is the login php code.
<?php
session_start();
require "dbc.php";
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$enc_password = md5($password);
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo "Logged in <a href='members.php'>Click here to enter the members area</a>";
$_SESSION['username']=$db_username;
header("location: members.php");
}
else
{
header("location: index.php?error=Incorrect Password");
}
}
else
{
header("location: index.php?error=That user doesn't exist");
}
}
else
{
header("location: index.php?error=All fields are required");
}
?>
The problem is I kept getting the "Incorrect Password" when I try to log in. I think theres something with retrieving the password from the database. Anyone can help?
You need to use $enc_password instead of $password in line:
if($username==$db_username&&$password==$db_password)
P.S. Also if you use md5 then don't do mysql_real_escape_string(), md5 will change your string and all injects will be removed.
P.P.S. Use PDO instead of mysql_*
UPDATE
Also username must be case insensitive so better to do:
if(strcasecmp($username, $db_username)===0 && $password==$db_password)
strcasecmp
change
if($username==$db_username&&$password==$db_password)
to
if($username == $db_username && $enc_password == $db_password)
You are using $password but it should be $enc_password
you're comparing $password with $db_password while you should be comparing $enc_password with $db_password.
if($username==$db_username&&$enc_password==$db_password)
In your case you should compare like this
$password = md5($password);//change value entered of password to md5
if($username==$db_username&&$password==$db_password)