Related
I have been trying to get my session update, I have created a basic update with mysql as well, it updates in the sql database but it will not show the change within the page.
I'm not sure what else to check, because I checked within the chrome settings and it does show a php session id value but if I go into session storage it shows nothing.
transaction.php
<?php
$_title = 'Update profile';
require_once(__DIR__.'../../components/header.php');
session_start();
if(! isset($_SESSION['user_name'])){
header('Location: ../sign_in/sign_in.php');
die();
}
if (!isset($_SESSION["lang"])) { $_SESSION["lang"] = "en"; }
if (isset($_POST["lang"])) { $_SESSION["lang"] = $_POST["lang"]; }
require_once(__DIR__.'../../globals.php');
require_once(__DIR__.'../../db.php');
try{
$db = _db();
}catch(Exception $ex){
_res(500, ['info'=>'System under maintainance','error'=>__LINE__]);
}
$userProduct = $_SESSION['user']['user_id'];
$q = $db->prepare('SELECT * FROM users WHERE user_id = :userID');
$q->bindValue(":userID", $userProduct);
$q->execute();
require "../lan/lang." . $_SESSION["lang"] . ".php";
?>
<form class="style_form" id="update_profile" onsubmit="return false">
<div>
<label for="name"><?=$_TXT[63]?></label>
<input type="text" name="name" value="<?php echo $_SESSION['user']['user_name']?>">
</div>
<div>
<label for="last_name"><?=$_TXT[64]?></label>
<input type="text" name="last_name" value="<?php echo $_SESSION['user']['lastName']?>">
</div>
<div>
<label for="email"><?=$_TXT[65]?></label>
<input name="email" value="<?php echo $_SESSION['user']['email']?>" type="text">
<input type="hidden" name="userId" value="<?php echo $_SESSION['user']['user_id'] ?>">
<button onclick="update()" id="updateButton"><?=$_TXT[60]?></button>
</form>
</section>
<?php
require_once(__DIR__.'../../components/footer.php');
?>
api-transaction.php
<?php
require_once(__DIR__.'../../globals.php');
// Validate name
if( ! isset( $_POST['name'] ) ){ _res(400,['name is required']); }
if( strlen( $_POST['name'] ) < _FRIST_NAME_MIN_LEN ){ _res(400,['name min '._FRIST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['name'] ) > _FRIST_NAME_MAX_LEN ){ _res(400,['name max '._FRIST_NAME_MAX_LEN.' characters']); }
// Validate last_name
if( ! isset( $_POST['last_name'] ) ){ _res(400,['last_name is required']); }
if( strlen( $_POST['last_name'] ) < _LAST_NAME_MIN_LEN ){ _res(400,['last_name min '._LAST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['last_name'] ) > _LAST_NAME_MAX_LEN ){ _res(400,['last_name max '._LAST_NAME_MAX_LEN.' characters']); }
// Validate email
if( ! isset( $_POST['email'] ) ){ _res(400,['email is required']); }
if( ! filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL ) ){ _res(400,['email is invalid']); }
$db = require_once(__DIR__.'../../db.php');
try{
session_start();
// $userid = $_SESSION['userId'];
// $userid = $_SESSION['user']['user_id'];
$userid = $_POST['userId'];
$db->beginTransaction();
//Change name
$q = $db->prepare('UPDATE users SET user_name = :update_Name WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_Name', $_POST['name']);
$q->execute();
//Change last name
$q = $db->prepare('UPDATE users SET lastName = :update_lastName WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_lastName', $_POST['last_name']);
$q->execute();
//change email
$q = $db->prepare('UPDATE users SET email = :update_email WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_email', $_POST['email']);
$q->execute();
// change phone number
$q = $db->prepare('UPDATE users SET phone_number = :update_phone WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_phone', $_POST['phone_number']);
$q->execute();
$db->commit();
header('Content-Type: application/json');
$response = ["info" => "info has been updated"];
echo json_encode($response);
}catch(Exception $ex){
http_response_code(500);
echo $ex;
echo 'System under maintainance';
exit();
}
I am currently trying to find out why my login statement works with using a username, but not email (or vice versa if switch in query)
The query only seems to accept the first value of the query, even if I've put it in brackets, it doesn't seem to register the second parameter.
Running the query in phpMyAdmin works flawlessly, but breaks in the script
open to suggestions
$sql = "SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID, $password])){
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=nouser");
exit();
}
I have tried
$sql = "SELECT * FROM db_cms_users WHERE (username = ? OR email = ?) AND password = ?";
rowCount returns true if I input a username, but false if I input a email. statements match SQL Database.
Dumped Variables
SQL: [76] SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?
Sent SQL: [137] SELECT * FROM db_cms_users WHERE username = 'test#email.com' OR email = 'test#email.com' AND password = 'password'
Params: 3
Key: Position #0: paramno=0 name=[0] "" is_param=1 param_type=2
Key: Position #1: paramno=1 name=[0] "" is_param=1 param_type=2
Key: Position #2: paramno=2 name=[0] "" is_param=1 param_type=2
Database output
Array
(
[0] => Array
(
[id] => 1
[0] => 1
[username] => test
[1] => test
[password] => $2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau
[2] => $2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau
[email] => test#email.com
[3] => test#email.com
[status] => 1
[4] => 1
[is_admin] => 1
[5] => 1
[registration] => 2021-11-13 12:21:28
[6] => 2021-11-13 12:21:28
)
)
File: user.class.php
protected function loginUser($userID, $password){
$sql = "SELECT password FROM db_cms_users WHERE username = ? OR email = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID])){
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=loginerror");
exit();
}
$hashedPwd = $stmt->fetchAll();
$checkPwd = password_verify($password, $hashedPwd[0]['password']);
if($checkPwd == false){
$stmt = null;
header("location: index.php?error=wrongpwd");
exit();
}elseif($checkPwd == true){
$sql = "SELECT * FROM db_cms_users WHERE username = ? OR email = ? AND password = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID, $password])){
#$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0){
$stmt = null;
header("location: login.php?error=nouser");
exit();
}
$row = $stmt->fetchAll();
//make session later
//nov 13/21
session_start();
$_SESSION['username'] = $row[0]['username'];
$_SESSION['uid'] = $row[0]['id'];
return true;
}
}
File userContr.class.php
public function login($userID, $password){
$result = $this->loginUser($userID, $password);
return $result;
}
File test.php
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include "includes/autoloader.inc.php";
$userObj = new UserView();
$data = $userObj->showUser(1);
echo "<pre>";
print_r ($data[0]);
echo "</pre>";
$userObj = new UserContr();
if(isset($_SESSION['uid'])){
echo "<h1>Welcome back ". $_SESSION['username'] ."!";
echo "<a href='?a=logout'>Logout</a>";
if(isset($_GET['a'])){
$a = $_GET['a'];
if($a == "logout"){
$userObj->logoutUser();
exit();
}
}
}else{
if(isset($_POST['loginUser'])){
$userID = $_POST['userid'];
$password = $_POST['password'];
$result = $userObj->login($userID, $password);
if($result == true){
header("location: index.php");
exit();
}else{
echo "There was a login error";
exit();
}
}else{
echo "<h1>Login</h1>";
echo "<form method='post' action>
<input type='text' name='userid' placeholder='Username/Email'>
<input type='password' name='password' placeholder='password'><br>
<input type='submit' name='loginUser' value='Login'>
</form>";
}
}
ob_end_flush();
SQL: Dump file
-- Table structure for table `db_cms_users`
--
CREATE TABLE `db_cms_users` (
`id` int(11) NOT NULL,
`username` text NOT NULL,
`password` text NOT NULL,
`email` text NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
`is_admin` int(11) NOT NULL DEFAULT '0',
`registration` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `db_cms_users`
--
INSERT INTO `db_cms_users` (`id`, `username`, `password`, `email`, `status`, `is_admin`, `registration`) VALUES
(1, 'test', '$2y$10$QNKXEo3pnGPCjUMnfXlV..JJ4OFcSQJ5EVg75xOjlE7p5pL7Dqwau', 'test#email.com', 1, 1, '2021-11-13 20:21:28');
Thanks for the big update. The context is very useful. It seems like what you're trying to do isn't logical or necessary.
To begin with, everything starts off well. In your loginUser() function, you're correctly fetching the user details based on the email / username. Then you're verifying the password the right way using password_verify(). That's all fine and sensible.
But the bit you seem to be having trouble with doesn't make a whole lot of sense. It looks like after you've verified the password, you then make another query to get the same user - except that this time you're trying to put the password into the WHERE clause. This makes no sense because
You've already found the user with the first query and verified them, and
the raw password will never match the one in the database because the one in the database is hashed (as it should be, hence why you used password_verify() earlier in the code).
You really don't need that second SELECT query - what are you trying to achieve with it?
If you just change the first query to select more fields, then your problem is solved - you can put those details directly into the Session without needing to run another query:
protected function loginUser($userID, $password) {
$sql = "SELECT username, id, password FROM db_cms_users WHERE username = ? OR email = ?";
$stmt = $this->connect()->prepare($sql);
if(!$stmt->execute([$userID, $userID])) {
$stmt = null;
header("location: index.php?error=failstmt");
exit();
}
if($stmt->rowCount() == 0) {
$stmt = null;
header("location: login.php?error=loginerror");
exit();
}
$user = $stmt->fetchAll();
$checkPwd = password_verify($password, $user[0]['password']);
if($checkPwd == false) {
header("location: index.php?error=wrongpwd");
exit();
}
elseif($checkPwd == true) {
session_start();
$_SESSION['username'] = $user[0]['username'];
$_SESSION['uid'] = $user[0]['id'];
return true;
}
}
P.S. Security best practice recommends that when the credentials are not valid you don't let the user know whether it was the username or password (or both) which was the problem. For example if you disclose that the username was wrong, it indicates to a malicious party that they can discard that username and try another one, and equally if you disclose that only the password is incorrect you are indicating that they should keep attempting to crack the password for that username. You should simply state "invalid credentials" in either case, which then does not give any clues about how to narrow the search for a valid login.
I get this error when i try to login
however the login email and password is already in the MySql database and they have been entered correctly. I am trying to make a website to calculate the odds of winning different types of gambling games and I am going to store the data on the database for each individual user so that they can view it later.
Thanks
login.php
<?php
include('header.html');
if (isset($errors)&& !empty($errors))
{
echo ' <p id="err_msg">Oops! there was a problem:<br>';
foreach ($errors as $msg )
{
echo " - $msg <br>";
}
echo 'Please try again or register here</p>';
}
?>
<form action="login_action.php" method="POST">
<dl>
<dt>Email : <input type="text" name="email"><dd>
<dt>Password: <input type="password" name="pass"><dd>
</dl>
<button type="submit">Login</button>
</form>
register.php
<?php
$page_title = 'GambCalc - Register';
include('header.html');
if ( $_SERVER['REQUEST_METHOD']=='POST')
{
require ('db_connection.php');
$errors = array();
if (empty($_POST['email']))
{$errors[] = 'Enter your first name.' ; }
else
{$e = mysqli_real_escape_string($dbc,trim($_POST['email']));}
if (empty($_POST['pass']))
{$errors[] = 'Enter your password.' ; }
else
{$p = mysqli_real_escape_string($dbc,trim($_POST['pass']));}
if (empty($errors))
{
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query($dbc,$q);
if (mysqli_num_rows($r) != 0)
$errors[] = 'Email address already registered. Login';
}
if (empty($errors))
{
$q = "INSERT INTO users (email, pass) VALUES ('$e',SHA1('$p'))";
$r = mysqli_query($dbc,$q);
if($r)
{
echo '<h1>Registered!</h1>
<p>Login</p>';
}
mysqli_close($dbc);
exit();
}
else
{
echo '<h1>Error!</h1>
<p id="err_msg">The folloiwng error(s) occurred:<br>';
foreach($errors as $msg )
{
echo " - $msg<br>";
}
echo 'Please try again </p>';
mysqli_close($dbc);
}
}
?>
<h1>Register</h1>
<form action="register.php" method="POST">
<p>
Email address : <input type="text" name="email"
value="<?php if ( isset($_POST['email']))
echo $_POST['email'];?>">
</p>
<p>Password : <input type="password" name="pass" value="<?php if(isset($_POST['pass'])) echo $_POST['pass'];?>"></p>
<p><input type="submit" value="Register"></p>
</form>
login_tools.php
<?php # LOGIN HELPER FUNCTIONS.
# Function to load specified or default URL.
function load( $page = 'login.php' )
{
# Begin URL with protocol, domain, and current directory.
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'PHP_SELF' ] ) ;
# Remove trailing slashes then append page name to URL.
$url = rtrim( $url, '/\\' ) ;
$url .= '/' . $page ;
# Execute redirect then quit.
header( "Location: $url" ) ;
exit() ;
}
# Function to check email address and password.
function validate( $dbc, $email = '', $pwd = '')
{
# Initialize errors array.
$errors = array() ;
# Check email field.
if ( empty( $email ) )
{ $errors[] = 'Enter your email address.' ; }
else { $e = mysqli_real_escape_string( $dbc, trim( $email ) ) ; }
# Check password field.
if ( empty( $pwd ) )
{ $errors[] = 'Enter your password.' ; }
else { $p = mysqli_real_escape_string( $dbc, trim( $pwd ) ) ; }
# On success retrieve user_id, first_name, and last name from 'users' database.
if ( empty( $errors ) )
{
$q = "SELECT user_id FROM users WHERE email='$e' AND pass=SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array ( $r, MYSQLI_ASSOC ) ;
return array( true, $row ) ;
}
# Or on failure set error message.
else { $errors[] = 'Email address and password not found.' ; }
}
# On failure retrieve error message/s.
return array( false, $errors ) ;
}
login_action.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
require ( 'db_connection.php' ) ;
require ( 'login_tools.php' ) ;
list ( $check, $data ) = validate ( $dbc, $_POST[ 'email' ], $_POST[ 'pass' ] ) ;
if ( $check )
{
session_start();
$_SESSION[ 'user_id' ] = $data[ 'user_id' ] ;
load('home.php');
}
else { $errors = $data; }
mysqli_close( $dbc ) ;
}
include ( 'login.php' ) ;
?>
Because in your query, it filtered the email with '$e' values. I think you should change it into something like this...
$q = "SELECT user_id FROM users WHERE email='".$e."'";
for checking, you can use var_dump or print_r
You should also update your other queries with the same format.
$q = "INSERT INTO users (email, pass) VALUES ('".$e."',SHA1('".$p."'))";
Change your query to $q = "SELECT user_id FROM users WHERE email='".$e."'";
I am using a panel that I am unfamiliar with; my friends and I can't seem to resolve this issue. I've looked for missing commas and values that might not add up however can't seem to see a solution.
I keep getting the error: MySQL Error: Column count doesn't match value count at row 1 so I thought I'd see if any good internet Samaritan would lend a hand.
Any help is appreciated!
<?php
if( !preg_match( "/index.php/i", $_SERVER['PHP_SELF'] ) ) { die(); }
if( $_GET['id'] ) {
$id = $core->clean( $_GET['id'] );
$query = $db->query( "SELECT * FROM users WHERE id = '{$id}'" );
$data = $db->assoc( $query );
$data['ugroups'] = explode( ",", $data['usergroups'] );
$editid = $data['id'];
}
?>
<?php
$query = $db->query("SELECT * FROM users WHERE username = '{$username}'");
$array = $db->assoc($query);
if ($user->data['id'] == "{$editid}") {
$db->query( "INSERT INTO logs VALUES (NULL, 'Attempted to edit own account <font color=\"FF0000\"><b>Denied</b></font>', NULL, '<b>{$user->data['fullUsername']}</b> ({$_SERVER['REMOTE_ADDR']})', '1') " );
die("<div class=\"square bad\">
<strong>Error</strong><br>
You cant not edit your own account! Log Inserted!</div>"); }
?>
<form action="" method="post" id="addUser">
<div class="box">
<div class="square title">
<strong>Edit User</strong>
</div>
<?php
if( $_POST['submit'] ) {
try {
$username = $core->clean( $_POST['username'] );
$password = $core->clean( $_POST['password'] );
$email = $core->clean( $_POST['email'] );
$habbo = $core->clean( $_POST['habbo'] );
$dgroup = $core->clean( $_POST['dgroup'] );
$banned = $core->clean( $_POST['banned'] );
$jobtitle = $core->clean( $_POST['jobtitle'] );
$forumuser = $core->clean( $_POST['forumuser'] );
$skypeuser = $core->clean( $_POST['skypeuser'] );
$notes = $core->clean( $_POST['notes'] );
$query = $db->query( "SELECT * FROM usergroups" );
while( $array = $db->assoc( $query ) ) {
if( $_POST['ugroup-' . $array['id']] ) {
$ugroups .= $array['id'] . ",";
}
}
$password_enc = $core->encrypt( $password );
if( !$username or ( !$password and !$editid ) or !$dgroup or !$ugroups ) {
throw new Exception( "All fields are required." );
}
else {
if( $editid ) {
if( $password ) {
$password = ", password = '{$password_enc}'";
}
else {
unset( $password );
}
$db->query( "UPDATE users SET username = '{$username}', password = '{$password}', email = '{$email}', habbo = '{$habbo}', displaygroup = '{$dgroup}', usergroups = '{$ugroups}', banned = '{$banned}', jobtitle = '{$jobtitle}', forumuser = '{$forumuser}', skypeuser = '{$skypeuser}', notes = '{$notes}', WHERE id = '{$editid}'" );
}
else {
$db->query( "INSERT INTO users VALUES (NULL, '{$username}', '{$password_enc}', '{$email}', '{$habbo}', '{$dgroup}', '{$ugroups}', '{$banned}', '{$jobtitle}', '{$forumuser}', '{$skypeuser}', '{$notes}');" );
}
echo "<div class=\"square good\">";
echo "<strong>Success</strong>";
echo "<br />";
echo "User added!";
echo "</div>";
$db->query( "INSERT INTO logs VALUES (NULL, 'Edited user $username <font color=\"51c833\"><b>Success</b></font>', NULL, '<b>{$user->data['fullUsername']}</b> ({$_SERVER['REMOTE_ADDR']})', '1') " );
}
}
catch( Exception $e ) {
echo "<div class=\"square bad\">";
echo "<strong>Error</strong>";
echo "<br />";
echo $e->getMessage();
echo "</div>";
$db->query( "INSERT INTO logs VALUES (NULL, 'Edited user $username <font color=\"FF0000\"><b>Fail</b></font>', NULL, '<b>{$user->data['fullUsername']}</b> ({$_SERVER['REMOTE_ADDR']})', '1') " );
}
}
?>
<table width="100%" cellpadding="3" cellspacing="0">
<?php
if ($data['banned'] == "1") {
?>
<div style="background: red; border: 1px solid black; padding: 5px;"><strong>User is currently banned!</strong></div>
<?php
}
// User Management Display Group
if ($user->data['displaygroup'] == "4") {
$db->query( "INSERT INTO logs VALUES (NULL, 'Edit User, Wrong Perms <font color=\"FF0000\"><b>Denied</b></font>', NULL, '<b>{$user->data['fullUsername']}</b> ({$_SERVER['REMOTE_ADDR']})', '1') " );
die("<div class=\"square bad\">
<strong>Error</strong><br>
You have the Incorrect Display group, Please contact an Administrator for assistance</div>"); }
// Radio Management Display Group
else if ($user->data['displaygroup'] == "39") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// Forum Events Management Display Group
else if ($user->data['displaygroup'] == "52") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// Events Management Display Group
else if ($user->data['displaygroup'] == "41") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// News Management Display Group
else if ($user->data['displaygroup'] == "40") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// Community Manager Display Group
else if ($user->data['displaygroup'] == "38") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// Administrator Display Group
else if ($user->data['displaygroup'] == "31") {
$query = $db->query( "SELECT * FROM usergroups WHERE admin = '1'" );
}
// Panel Administrator Display Group
else if ($user->data['displaygroup'] == "32") {
$query = $db->query( "SELECT * FROM usergroups WHERE snradmin = '1'" );
}
// Developer Display Group
else if ($user->data['displaygroup'] == "42") {
$query = $db->query( "SELECT * FROM usergroups WHERE mgmt = '1'" );
}
// Owner Display Group
else if ($user->data['displaygroup'] == "5") {
$query = $db->query( "SELECT * FROM usergroups" );
}
else {
// Random code to hide the page from everyone else
die("<div class=\"square bad\">
<strong>Error</strong><br>
Sorry you do not have the correct permission to view this page! Contact an admin!</div>");
}
while( $array = $db->assoc( $query ) ) {
if( in_array( $array['id'], $data['ugroups'] ) ) {
$groups[$array['id'] . '_active'] = $array['name'];
}
else {
$groups[$array['id']] = $array['name'];
}
if( $array['id'] == $data['displaygroup'] ) {
$dgroups[$array['id'] . '_active'] = $array['name'];
}
else {
$dgroups[$array['id']] = $array['name'];
}
}
$opt_banned = Array (
"0" => "Active",
"1" => "Banned"
);
echo $core->buildField( "text",
"required",
"username",
"Username",
"The new username.",
$data['username'] );
echo $core->buildField( "password",
"<?php if( !$editid ) { ?>required<?php } ?>",
"password",
"Password",
"" );
echo $core->buildField( "text",
"",
"email",
"Email",
"The new email (optional).",
$data['email'] );
echo $core->buildField( "text",
"",
"habbo",
"Habbo name",
"Staff Members Habbo Name",
$data['habbo'] );
echo $core->buildField( "text",
"",
"jobtitle",
"Job Title",
"The staff members job title",
$data['jobtitle'] );
echo $core->buildField( "text",
"",
"forumuser",
"forum username",
"The staff members forum Username",
$data['forumuser'] );
echo $core->buildField( "text",
"",
"skypeuser",
"Skype username",
"The staff members skype useranme",
$data['skypeuser'] );
echo $core->buildField( "left_textarea",
"",
"Notes",
"Acc Notes",
"The staff members Notes",
$data['notes'] );
echo $core->buildField( "select",
"",
"banned",
"Banned",
"To ban a user, enter 1, thus restricting them from logging in or 0 to not ban.",
$opt_banned );
echo $core->buildField( "select",
"required",
"dgroup",
"Display group",
"The user's display group.",
$dgroups );
echo $core->buildField( "checkbox",
"required",
"ugroup",
"Active usergroups",
"The user's active groups.",
$groups );
?>
</table>
</div>
<div class="box" align="right">
<input class="button" type="submit" name="submit" value="Submit" />
</div>
</form>
<?php
echo $core->buildFormJS('addUser');
?>
You didn't post your table structure, but simply: your number of values doesn't match the number of columns in your table 'logs'.
If I looked at it right, your query breaks down to this:
$value1 = 'Attempted to edit own account <font color=\"FF0000\"><b>Denied</b></font>';
$value2 = $user->data['fullUsername'];
$value3 = $_SERVER['REMOTE_ADDR'];
$query = "INSERT INTO logs VALUES (NULL, '$value1', NULL, '<b>$value2</b> ($value3)', '1')";
I don't see where you specify which columns to insert those values into.... How can we determine a mismatch without table structure?
example from my DB:
INSERT INTO articles(id, title, content, createdby, lastmodified) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
I've worked with Radipanel before its a interesting system. I personally can't see the issue with this piece of code, are you getting an error after you submit the form? If so it could be a column name mismatch, radipanel is very specific in the way that it collects table information.
This question already has answers here:
Best way for a 'forgot password' implementation? [closed]
(10 answers)
Closed 2 years ago.
I have a database of usernames and passwords. I need to create a "Forgot password" function and have it search the table for a username and return that user's password. Then I would like it to send an email saying the name and password.
Here is my working code for querying the database for a specific user:
<?php
session_start();
include "config.php";
if($_POST['nameQuery']) {
$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
//User exists
echo '1';
} else {
mysql_query($query);
//User does not exist
echo '0';
}
}
?>
DO NOT store passwords in your database. Cleartext passwords should never be stored. You should be storing a hash of the passwords to help prevent them being used on other sites. See Best way to store password in database for more information.
Your code is NOT secured ! Your $_POST['nameQuery'] is a gorgeous opened door to SQL Injection
The minimum security is to escape and sanitize all your inputs
$nameQuery = mysql_real_escape_string ($_POST['nameQuery']);
The golden rule: never trust incoming data.
Community Wiki:
Don't. Because that means you'll be saving retrievable passwords. Better to send a password-changing link to their email that gives access to a one-time password reset page. In this way, the password isn't changed until a reset cycle is completed by someone with access to that user's email.
In that way you can appropriately hash passwords and check incoming passwords against a hash only.
In addition, I recommend looking into php's PDO, because you're currently creating sql queries that are succeptible to sql-injection.
I have a few suggestions for you
Don't send people there password but rather provide them with a link to change there password
Look into kjetilh's suggestion
good luck and happy coding
First thing's first: you might want to make sure that you won't get SQL-injected via your login, as you're literally injecting the user input into your query... big no-no.
Swap this:
$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";
...for this:
$query = sprintf(
'SELECT * FROM myDatabase WHERE name = \'%s\'',
mysql_real_escape_string($_POST['nameQuery'])
);
Next up is what you asked for: a way to get both the users username and password. While I don't recommend that you actually store the password in plaintext for everyone to view, it's a decision you have to make on your own.
This snippet will do the deed:
<?php
//Get the data from the DB
$query = sprintf(
'SELECT * FROM myDatabase WHERE name = \'%s\'',
mysql_real_escape_string($_POST['nameQuery'])
);
$result = mysql_query($query);
$user_info = mysql_fetch_assoc($result);
//Check if it's valid
if( isset($user_info['name']) ) {
//Construct the message
$message = 'Your username is: ' . $user_info['name'] . "\n"
$message .= 'Your password is: ' . $user_info['password'] . "\n";
//Send it to the appropriate email
$status = mail(
$user_info['email'],
'Password recovery for ' . $user_info['name'],
$message
);
//Check if it actually worked
if( $status ) echo 'Mail sent. Check your inbox. Login again. Thank you.';
else echo 'The password recovery couldn\'nt be sent. Please try again later.';
} else {
echo 'No user found with the supplied username.',
'Please try again (with another username)';
}
?>
Edit: Adding password recovery-functionality
For the password recovery-functionality you requested below, you can try something like this:
recover_password.php:
<?php
session_start();
//mysql_connect()-here
//Initalize the variable
$do_update_password = false;
//Grab the token
$token = isset($_REQUEST['token'])? $_REQUEST['token'] : '';
$is_post_request = isset($_POST['update_pwd'])? true : false;
$is_recovery_request = isset($_POST['request_recovery'])? true : false;
$message = '';
//Check if we're supposed to act upon a token
if( $is_recovery_request ) {
//Grab the email
$email = isset($_POST['email'])? $_POST['email'] : '';
//Create the query, execute it and fetch the results
$sql = sprintf(
'SELECT `user_id` FROM myDatabase WHERE `email` = \'%s\'',
mysql_real_escape_string($email)
);
$result = mysql_query($sql);
$user_info = mysql_fetch_assoc($result);
//Validate the response
if( isset($user_info['user_id') ) {
//Let's generate a token
$date = date('Y-m-d H:i:s');
$token = md5($email . $date);
//Create the "request"
$sql = sprintf(
'INSERT INTO myRequests (`user_id`, `token`, `date`) VALUES (\'%s\', \'%s\', \'%s\')',
$user_info['user_id'],
mysql_real_escape_string($token),
$date
);
$result = mysql_query($sql);
//Validate
if( mysql_affected_rows($result) == 1 ) {
//Construct the message
$message = 'Your username is: ' . $user_info['email'] . "\n"
$message .= 'Please click on the following link to update your password: http://yoursite.com/request_password.php?token=' . $token . "\n";
//Send it to the appropriate email
$status = mail(
$email,
'Password recovery for ' . $email,
$message
);
//Check if it actually worked
if( $status ) {
echo 'Mail sent. Check your inbox. Login again. Thank you.';
} else {
echo 'The password recovery couldn\'nt be sent. Please try again later.';
}
} else {
$message = 'The DB-query failed. Sorry!';
}
} else {
$message = 'The specified e-mail address could not be found in the system.';
}
} elseif( $token != '' ) {
//Check so that the token is valid length-wise (32 characters ala md5)
if( !isset($token[31]) || !isset($token[32]) ) {
$message = 'Invalid token!';
} else {
//Construct the query and execute it
$sql = sprintf(
'SELECT `user_id` FROM myRequest WHERE `token` = \'%s\'',
mysql_real_escape_string($token);
);
$result = mysql_query($sql);
//Fetch the rows
$request_info = mysql_fetch_assoc($result);
//Check for a valid result
if( isset($request_info['user_id']) ) {
$message = 'Update your password below.';
$do_update_password = true;
} else {
$message = 'No record found for the following token: ' . $token);
}
}
} elseif( $is_post_request ) {
//Grab the new password
$password = isset($_POST['password'])? $_POST['password'] : '';
//Construct the query
$sql = sprintf(
'UPDATE myDatabase SET `password` = \'%s\' WHERE `user_id` = ( SELECT `user_id` FROM myRequest WHERE `token` = \'%s\' )',
mysql_real_escape_string($password),
mysql_real_escape_string($token)
);
//Execute it, and check the results
$result = mysql_query($sql);
if( $result !== false ) {
//Did we succeed?
if( mysql_affected_rows($result) === 1 ) {
//Remove the old recovery-request
$sql = sprintf(
'DELETE FROM myRequests WHERE `token` = \'%s\'',
mysql_real_escape_string($token)
);
$result = mysql_query($sql);
//^We don't actually need to validate it, but you can if you want to
$message = 'Password updated. Go have fun!';
} else {
$message = 'Could not update the password. Are you sure that the token is correct?';
}
} else {
$message = 'Error in the SQL-query. Please try again.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password recovery</title>
<style>
form > * { display: block; }
</style>
</head>
<body>
<h1><?php echo $message; ?></h1>
<?php if( $do_update_password ): ?>
<form method="post">
<label for="token">Token:</label>
<input type="text" name="token" id="token" value="<?php echo $token; ?>" />
<label for="password1">Password:</label>
<input type="text" name="password[]" id="password1" />
<label for="password2">Password (again):</label>
<input type="text" name="password[]" id="password2" />
<input type="submit" name="update_pwd" value="Update your password!" />
</form>
<?php elseif($is_post_request && $token != ''): ?>
<h2>Request that might've updated your password. Exciting!</h2>
<?php else: ?>
<form method="post">
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" />
<input type="submit" name="request_recovery" value="Request a new password" />
</form>
<?php endif; ?>
</body>
</html>
Note that I haven't had time to actually test the code, but I think it'll work just fine with some minor adjustments. Oh, before I forget, you'll need to add the following table to the DB:
Table structure for table myRequests
CREATE TABLE IF NOT EXISTS `myRequests` (
`request_id` int(6) NOT NULL AUTO_INCREMENT,
`token` varchar(32) NOT NULL,
`user_id` int(6) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`request_id`),
UNIQUE KEY `token` (`token`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Good luck!
While tangential to your original question, I would like to point out that storing passwords in plain text is a bad idea. You should store hashed versions of the password in the database. You can then hash user input and compare it to what is in the database for logging in.
Instead, your forgot password should create a new(temporary) password, and store the hash of that in the database, while sending the plain text password to the email account on file.
Just read the result:
/* ... */
if (mysql_num_rows($result) > 0) {
// User exists
$row = mysql_fetch_row($result);
print_r($row);
}
/* ... */
On a more general note: You have a SQL injection vulnerability in your code, please look into that topic, or attackers will be able to read all your user's passwords.
Also, it is not advised to store the password in clear text in you database. Please use a hashing algorithm like sha1 oder sha256 to store passwords.
I will recommend you to change your table design to
UserName
Password ' store hash
Password Retrieval Question ' store hash
Password Retrieval Answer ' store hash
When login check the user against the hashed password, something like this
$_POST['password']=sha1($_POST['password']);
When loggin in then use sql like
select col1,col2,.. from tbl where user=? and password=? and then fill the parameter with $_POST['username'], $_POST['password']
so use Prepared Statement or PDO
use the same logic when user forgot his password
<?php
session_start();
include "config.php";
if($_POST['nameQuery']) {
$query = "SELECT * FROM myDatabase WHERE name = '" .mysql_real_escape_string($_POST['nameQuery']). "'";
$result = mysql_query($query) or die ('Error: '.mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$message = 'Your password is: '.$row['password'];
if(mail($row['user_email'], 'Lost password', $message)){
echo 'Password sent';
}
} else {
echo 'Nu such user';
}
}
?>
You have to retrieve the username and password from the mysql_query result (stored in the $result variable) as such:
$row = mysql_fetch_array($result);
$username = $row['username'];
$password = $row['password'];
Then use php's mail() function to send the e-mail.