I am just starting to learn php and sql so please go easy on me, i know i'm going to be wrong in certain places. I am trying to allow a user to login and be able to change their password. I have made an attempt of a script which i believe should work, but i guess i'm doing something wrong as it will just link to the php function page and not change the password at all. Here's my script:
HTML form:
<form method="POST" action="includes/changepassword.php">
<p><input type="password" name="oldpasswd" id="oldpasswd" maxlength="30" placeholder="Old Password"></p>
<p><input type="password" name="newpsswd1" id="newpsswd1" maxlength="30" placeholder="New Password"></p>
<p><input type="password" name="newpsswd2" id="newpsswd2"maxlength="30" placeholder="Confirm Password"></p>
<input type="submit" name="submit" id="submit" value="change password">
changepassword.php file:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
function changepassword ($oldpasswd, $newpasswd1, $newpasswd2) {
/*
* RETURNS
* 0 - if password changed
* 1 - if new passwords are not equal
* 2 - if user authentification problems
*/
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd1 = ($_POST['newpasswd1']);
$newpasswd1 = ($_POST['newpasswd2']);
if ($newpasswd1 != $newpasswd2) {
return 1;
}
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
if (md5($oldpasswd)==$result) {
//Encrypt $emailpassword in MD5 format for the database
$md5_np=md5($newpasswd1);
// Make a safe query
$query = sprintf("UPDATE `ptb_users` SET `password` = '%s'
WHERE `id` = ".$_SESSION['user_id'],
mysql_real_escape_string($md5_np));
mysql_query($query)or die('Could not update password: ' . mysql_error());
return 0;
} else {
return 2;
}
}
?>
What have I done wrong?
it will just link to the php function page and not change the password at all
You told the HTML form to do exactly that: <form method="POST" action="includes/changepassword.php">. But on the other hand, you never call your function.
You need to call the function in order to process the change password. Add this to the bottom of your file just before the ?>
echo changepassword($_POST['oldpasswd'], $_POST['newpasswd1'], $_POST['newpasswd2']);
You can also remove the $_POST assignments within the function as you're passing those in as parameters.
As poke mentioned you will need to call the function in order to update the password.
I think I found another problem in the following code:
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
if (md5($oldpasswd)==$result) {
You are directly using the result of the mysql_query() function which actually returns as a resource and not a value.
You will need to update your code to this:
//check user logged in changes OWN passwd
$sql = "SELECT password FROM ptb_users WHERE id = ".$_SESSION['user_id'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
$row=mysql_fetch_assoc($result);
if (md5($oldpasswd)==$row['password']) {
See this function- mysql_fetch_assoc().
Look for a tutorial about form handling, after a bit of searching if stumbled over this form tutorial, it looks easy to understand. You will see, that most forms call themself.
formchangepassword.html
<form action="formchangepassword.html" method="post">
At the begin of the form there is usually some code, that decides if the form was called with post (after pressing a button), or if it was called with get. In this code you can call the function you wrote in your CHANGEPASSWORD.PHP file. This file is just a library, it contains functions, you can call this function but they do not run themselfes, they have to be called.
<?php
require_once("CHANGEPASSWORD.PHP");
if(count($_POST) > 0)
{
// button was clicked, do what is necessary
changepassword(...);
...
}
?>
<form action="formchangepassword.html" method="post">
...
</form>
The name of your form fields doesn't match what's listed in changepassword.php . You are missing an "a" in what should be "newpasswd1" and "newpasswd2" -- name=newpsswd1 should be newpasswd1 and so on.
Also you have "newpasswd1" listed twice
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd**1** = ($_POST['newpasswd1']);
$newpasswd**1** = ($_POST['newpasswd2']);
...I think you probably meant this...
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd**1** = ($_POST['newpasswd1']);
$newpasswd**2** = ($_POST['newpasswd2']);
I also incorporated the changes suggested by Pastor Bones and Abhishek Bhatia and it works fine now. (Also I a close form tag to the HTML)
Here's what the whole thing should look (as modified for my site):
HTML FORM
<form method="POST" action="changepassword.php">
<p><input type="password" name="oldpasswd" id="oldpasswd" maxlength="30" placeholder="Old Password"></p>
<p><input type="password" name="newpasswd1" id="newpasswd1" maxlength="30" placeholder="New Password"></p>
<p><input type="password" name="newpasswd2" id="newpasswd2"maxlength="30" placeholder="Confirm Password"></p>
<input type="submit" name="submit" id="submit" value="change password">
</form>
changepassword.php
function changepassword ($oldpasswd, $newpasswd1, $newpasswd2)
{
$oldpasswd = ($_POST['oldpasswd']);
$newpasswd1 = ($_POST['newpasswd1']);
$newpasswd2 = ($_POST['newpasswd2']);
if ($newpasswd1 != $newpasswd2)
{
return 1;
}
$sql = "SELECT Password FROM users WHERE UserID = ".$_SESSION['UserId'];
$result = mysql_query($sql)or die('User not found: ' . mysql_error());
$row=mysql_fetch_assoc($result);
if (md5($oldpasswd)==$row['Password'])
{
$md5_np=md5($newpasswd1);
$query = sprintf("UPDATE `users` SET `Password` = '%s' WHERE `UserID` ".$_SESSION['UserId'],mysql_real_escape_string($md5_np));
mysql_query($query)or die('Could not update password: ' . mysql_error());
return 0;
}
else
{
return 2;
}
}
echo changepassword($_POST['oldpasswd'], $_POST['newpasswd1'], $_POST['newpasswd2']);
Related
the registration form is connected to the database via db.php but I am having trouble in submitting the login details.
<html>
<head>
<?php
include('db.php');
$username = #$_POST['username'];
$password = #$_POST['password'];
$submit = #$_POST['submit'];
the main problem is after the submit button is clicked by an existing user it should give the message but there's problem in the if statement, because on the wamp server its showing only the else message i.e. Error.
if ($submit)
{
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
if (mysql_num_rows($result)) {
$check_rows = mysql_fetch_array($result);
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
echo "<center>";
echo "You are now Logged In. ";
echo "</center>";
}
else {
echo "<center>";
echo "No User found. ";
echo "</center>";
}
}
else echo "Error";
?>
</head>
<body>
<form method="post">
Username : <input name="username" placeholder="Enter Username" type="text"><br></br>
Password : <input name="password" placeholder="Enter Password" type="password"><br>
<input type="submit" value="Submit">
</body>
</html>
You want get $_POST with name submit, but do not send it to the form
Try change
<input type="submit" value="Submit">
to
<input type="submit" name="submit" value="Submit">
Firstly this is old style of php/mysql. So look at PDO on php.net seeing as you are setting out on new project it really wont be hard to make the change now rather than later.
Now onto your issue. if you intend on carrying on with your old method try this.
$sql = "SELECT * FROM user WHERE username=' . $username . ' AND password=' . $password . '";
// check the query with the die & mysql_error functions
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
// checking here equal to 1 In a live case, for testing you could use >= but not much point.
if ($result == 1) {
// Checking needs to be Assoc Now you can use the field names,
// otherwise $check_rows[0], $check_rows[1] etc etc
$check_rows = mysql_fetch_assoc($query); // oops we all make mistakes, query not result, sorry.
// This is bad but for example il let this by,
// please dont access user supplied data without
// validating/sanitising it.
$_POST['username'] = $check_rows['username'];
$_POST['password'] = $check_rows['password'];
} else {
// do not logged in here
}
The same in PDO
$sql=" Your query here ";
$pdo->query($sql);
$pdo->execute();
$result = $pdo->fetch();
if ($result = 1) {
// do login stuff
} else {
// no login
}
Remember though that you need to set up PDO and it may not be available on your server by default (older php/mysql versions) but your host should be happy enough to set them up.
I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I'm trying at the moment to create a login with PHP and MySQL but I'm stuck. The array that's supposed to give me Data from the database only returns "Null" I used var_dumb().
This is the index.php file :
<?php
include_once './Includes/functions.php';
?>
<!DOCTYPE html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<form method="POST">
<label>User ID :</label>
<input id="login_username" name="login_username" type="login"><br>
<label>Password :</label>
<input id="login_password" name="login_password" type="password" ><br>
<input id="login_submit" name="login_submit" type="submit">
</form>
</div>
</body>
</html>
This is the function.php file :
<?php
require_once 'dbconnect.php';
function SignIn() {
$lUser = $_POST['login_username'];
$lPassword = md5($_POST['login_password']);
$querySQL = "SELECT * FROM tblUser WHERE dtUser='$lUser' AND dtPassword='$lPassword'";
$queryResult = mysqli_query($dbc, $querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
if ($lUser == $dataArrayLogin['dtUser'] && $lPassword == $dataArrayLogin['dtPassword']) {
echo $dataArrayLogin;
$popup = "Login Succeed";
echo "<script type='text/javascript'>alert('$popup');</script>";
$_SESSION['user'] = $lUser;
header("Location: ./british.php");
} else {
echo $dataArrayLogin;
$popup = "Login Failed";
echo "<script type='text/javascript'>alert('$popup');</script>";
}
}
if (isset($_POST['login_submit'])) {
SignIn();
}
?>
Could you help me out ?
This could be, because you have no results?
Anyway, I've checked your code, and it's not good, because you are try to use this:
$dataArrayLogin['dtUser']
There is no 'dtUser' key in your $dataArrayLogin.
When you fetching the row, you are put it into a while cycle, and collect the data into an array:
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayLogin[] = $row;
}
Remove the while cycle. Simple use:
$dataArrayLogin = mysqli_fetch_assoc($queryResult);
And if you echo an array, the result will be Array. Use var_dump instead.
in your html form, you don't have <form method="POST" action="SignIn">. so when you submit the form, its not going somewhere.
You need to start debugging your script. Below are the steps I would take:
Do a var_dump() on the $_POST to see if it contains all values you want
echo the $querySQL to see if all values are put in correctly
Check your database if it actually contains the record with which you are trying to login
Fetch mysql errors using mysqli_error();
That should bring your error to light.
Edit:
I often find it usefull to place some echos throughout my script to find out what parts of the code are being accessed and what parts are being skipped.
I would add a LIMIT 1 to your query as there should only be one user with the entered credentials. This way you'll also be able to skip the while loop.
Change query like this
$querySQL = "SELECT * FROM tblUser WHERE dtUser=' ".$lUser." ' AND dtPassword=' ".$lPassword." ' ";
I'm making a login page for the admins to make some changes to a website easily. However, the login page isn't working correctly. It won't go to the error page InvalidLogin.html and it won't go to the next page of the admin website AdminChanges.php.
Instead, I'm getting the following message:
Not Found
The requested URL /website/method="post" was not found on this server.
<?php
if ($_POST['submit'] == "submit")
{
$userName = $_POST['username'];
$passWord = $_POST['password'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$checkUserNameQuery = "SELECT username FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWordQuery = "SELECT password FROM onlineformdata ORDER BY id DESC LIMIT 1";
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
$AdminChanges = "AdminChanges.php";
}
else
{
$AdminChanges = "InvalidLogin.html";
}
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<form action = <?php PrepSQL($AdminChanges); ?> method="post">
username: <input type="text" name="username" />
password: <input type="text" name="password" /> <br/>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Two problems are joining forces to cause this error. First, your PrepSQL function does not echo the response, and neither does the code that calls it. You need to echo or print the response so that it appears in your generated HTML.
<?php echo PrepSQL($AdminChanges); ?>
Second, you need to encapsulate that value of the action attribute in double-quotes, like this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
Also note that your code assumes that your mysql_query() statements were successful. For troubleshooting purposes, you should at least add an or die(mysql_error()) statement to the end of the mysql_query() lines. This will allow your code to provide some feedback when the query fails.
Additionally, please note that your query-handling method will never result in a valid login response.
$checkUserName = mysql_query($checkUserNameQuery);
$checkPassWord = mysql_query($checkPassWordQuery);
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
mysql_query() returns a MySQL resource, not a single field from the database. Your code attempts to compare that resource to the supplied username and password, and the comparison will always fail. For details about handling the results of mysql_query() see the documentation.
Replace:
PrepSQL($AdminChanges);
with:
print PrepSQL($AdminChanges);
Try this:
<form action = "<?php echo PrepSQL($AdminChanges); ?>" method="post">
You need to echo the value.
There are 2 errors I noticed:
Your $_POST['submit'] if statement doesn't let $AdminChanges be set for the form unless it has already been submitted.
To fix this you could change your if submit statement to just redirect to your invalid login page like so:
if (($userName == $checkUserName) && ($passWord == $checkPassWord))
{
//Correct info do what you need to here
}
else
{
header("Location: InvalidLogin.html");
exit();
}
And also:
You need to change the action to go post to this page.
<form action="<? $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
I have a script that I'm using that when the user enters a code I want it to add to the total in the database, however nothing is happening.
This is my code so far:
$err = array();
if (isset($_POST['doSubmit4']) === true ) // Was if ($_POST['access']=='submit')
{
$code = mysql_real_escape_string($_POST['access-key']); // Was $data['access-key']
$result = mysql_query("SELECT `akid`,`key`,`total_access` FROM access_keys WHERE id='$_SESSION[user_id]' AND type='1'") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the key exists.
if ( $num > 0 ) {
list($akid,$key,$total_access) = mysql_fetch_row($result);
if ($code == $key) {
if(empty($err)){
$total_access++;
mysql_query("update access_keys set total_access='$total_access' where akid='$akid'") or die(mysql_error());
header("Location: ./");
}
} else {
$err[] = "Invalid Access Key. Please try again with correct access key.";
}
} else {
$err[] = "Error - Invalid Access Key. No access exists for your user ID.";
}
}
I'm wanting it to add to the Total Access field each time the user enters the correct code, but it's not working.
This is my form code:
<form name="postAccess" id="postAccess" method="post" action="access.php">
<input type="password" name="access-key" id="access-key" style="background-color:black;color:white;" size="40" /><br/>
<input name="doSubmit4" type="submit" id="doSubmit4" value="submit">
</form>
It might be your parent if brackets.
Try:
if (isset($_POST['access']) === true )
instead of
if ( $_POST['access']=='submit' )
If that doesn't seem to do it, do some debugging.
Throw some echo statements in those if brackets to see what conditions are true and what are not.
EDIT:
I just realized another problem.
Your form action is invalid. This should be the path to the page you are posting the data to. So:
Instead of:
<form name="access" id="access" method="post" action="access">
You should have:
<form name="access" id="access" method="post" action="your-php-path-here.php">
Notice how action = "your-php-path-here.php" in the above code.