How to reset password that is generated with md5() and crypt() - php

I was working on my project and I forget Admin users password. Here is users table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `users` (`id`, `email`, `password`, `name`) VALUES
(7, 'ikhlassons#gmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'Ikhlas Sons'),
(10, 'wali_essa#hotmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'essa');
Can anyone tell me how reset password in php that is generated with md5() and cryp()
Here's how the password is generated:
$hash = crypt($entered_password,"");
$hash = md5($hash);

You need an extra column named, for example, password_reset_token. When a user wants to recover his password, your app must generate a (long enough) random string and store it in than password_reset_token field.
Then you create a script that receives that token by $_GET (i.e.: example.com/password-reset/?token=982dh89h2w9h92hd), check if it exists in the Users table and, if correct, promtps a form to reset the password for that user.
You have to email that link (example.com/password-reset/?token=982dh89h2w9h92hd) to the user, telling him to click on it to reset his password.

This should work:
$hash = crypt("passpass","");
$hash = md5("passpass");
echo $hash;
Or this:
$hash = crypt("passpass","");
echo $hash;
Remember your password is passpass. Copy the code into users.password field in mysql database. And use passpass as password when login.

Related

How to allow mutilple page to insert multiple data at the same time (will not clash) in MySQL PHP

I have a online page which will allow user to create an account for them in order to acceess our page.
I worry in some period, there will be a lots of user who create at the same time.
In that case, I worry my database will be clash or conflict.
Can I know is that anyway to prevent that happens?
My table as below:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`userid` varchar(30) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`name` varchar(40) DEFAULT NULL
)
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
ADD UNIQUE KEY `userid` (`participant_id`);
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;
So my id will be just number and auto increment.
userid wil be unique.
I created the page by using PHP.
And I use following insert command at my page:
do {
$query = "INSERT IGNORE INTO user(userid, password, name) VALUES ('$userid','$password','$name')";
$insert = $conn->query($query);
} while( $insert && ($conn -> affected_rows == 0) );
Are this code can work perfectly to prevent the date conflit?
Another extra question is, how about if I create another extra page which will insert information 'user' table and can I used the same code at the new page?

MySQL: UNIQUE keys

I have a weird issue, well, weird in my eyes anyway.
I've got a database with ID, username, email, password etc...
The ID is the Primary key, and both the username and email have the UNIQUE key assigned.
Now the strange thing is, when I submit, lets say the following values;
username: ActionHank
email: ah#ah.com
it is added.
Now when I try adding the same values again, I get an error that it is not allowed since it would be a duplicate entry. This works great.
But, when I put in the following next;
username: ActionHank2
email: ah#ah.com
It just adds it again, so 2 users have the same e-mail address while I've given the email row the UNIQUE key. I could also just change the e-mail address instead of the username and it will be added. So somehow the MySQL only registers one of the UNIQUE keys or something, I'm confused.
Could someone help me on this matter? Thanks
Edit: I've used phpMyAdmin to create the table and exported it to SQL, here's how the create table looks:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`date_registered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip_address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
So I think it has a composite as Michael and Kingkero suggested. How can I solve this within phpMyAdmin?
You have defined the combination of username and email to be unique. If you want each to be unique, you need to define separate unique constraints:
create table . . .
unique username,
unique email
)
Or, because these are single columns, you can just do:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` varchar(25) NOT NULL UNIQUE,
`email` varchar(255) NOT NULL UNIQUE,
`password` varchar(255) NOT NULL,
`date_registered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip_address` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
Try this:
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)

on duplicate key update results in a high index key

so im using ON DUPLICATE KEY UPDATE when logging in - i am using it at every login because im getting the data from an external page and the users can only update their settings there. thats because the lack of an api by the software on that page.
actually im using this query to update their settings. if the account isnt listed in my database, its getting created with their credentials on success.
my problem is, that if the user isnt listed in my database and they are inserted into it, their id (auto increament) is not 1, 2, 3, 4 and so on. its starting at 32, then it goes to 54, after that 185 and so on. the ID raises so fast. is this an issue in my query or is this actually a bug?
http://puu.sh/8iXv7.png
heres my query
mysqli_query($database, " INSERT INTO `benutzer` (`id`, `login`, `vorname`, `nachname`, `gruppen`, `email`, `adresse`, `telefon`, `telefon2`, `telefon3`, `bemerkungen`)
VALUES (NULL, '".$userdata[0]."', '".$userdata[1]."', '".$userdata[2]."', '".implode(";", $gruppen)."', '".$userdata[3]."', '".$userdata[4]."', '".$userdata[5]."', '".$userdata[6]."', '".$userdata[7]."', '".$userdata[8]."')
ON DUPLICATE KEY UPDATE `vorname` = '".$userdata[1]."', `nachname` = '".$userdata[2]."', `gruppen` = '".implode(";", $gruppen)."', `email` = '".$userdata[3]."', `adresse` = '".$userdata[4]."', `telefon` = '".$userdata[5]."', `telefon2` = '".$userdata[6]."', `telefon3` = '".$userdata[7]."', `bemerkungen` = '".$userdata[8]."'") or die(mysql_error());
aand this is the structure of the table
CREATE TABLE IF NOT EXISTS `benutzer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(32) NOT NULL,
`vorname` text NOT NULL,
`nachname` text NOT NULL,
`gruppen` text NOT NULL,
`email` text NOT NULL,
`adresse` text NOT NULL,
`telefon` text NOT NULL,
`telefon2` text NOT NULL,
`telefon3` text NOT NULL,
`bemerkungen` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `login` (`login`),
KEY `login_2` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
thanks in advance
It's expected and documented behavior.
If you don't like it - then don't use the tool on the wrong purpose.
However, I wouldn't call it a problem at all. Id is an abstract identifier and lasts up to four billion, which ought to be enough for everyone

How to implement email verification with php?

I'm using php and laravel as a framework. I want to let user be able to activate their accounts through email.
I have no experience with this however. I already set up a form that asks for username, email and password.
Would this still be the best way to go about it in 2013?
http://net.tutsplus.com/tutorials/php/how-to-implement-email-verification-for-new-members/?search_index=8
So:
I need to create a database field for a hashed password.
On user account creation create a random password for this field and email it to them.
Provide link with the password and user id in the url to a page that compares the emailed password with password in db field.
Activate account(set active to 1) when the passwords match.
Something along those lines?
Email verification is a simple process there is two way to verify email either by sending code to user email address or by sending link both works same here is a sample code from a tutorial http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php on TalkersCode
// Table Scheme for Verify Table
CREATE TABLE `verify` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` text NOT NULL,
`password` text NOT NULL,
`code` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
// Table Scheme for verified_user table
CREATE TABLE `verified_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` text NOT NULL,
`password` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
if(isset($_POST['register']))
{
$email_id=$_POST['email'];
$pass=$_POST['password'];
$code=substr(md5(mt_rand()),0,15);
mysql_connect('localhost','root','');
mysql_select_db('sample');
$insert=mysql_query("insert into verify values('','$email','$pass','$code')");
$db_id=mysql_insert_id();
$message = "Your Activation Code is ".$code."";
$to=$email;
$subject="Activation Code For Talkerscode.com";
$from = 'your email';
$body='Your Activation Code is '.$code.' Please Click On This link Verify.php?id='.$db_id.'&code='.$code.'to activate your account.';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
echo "An Activation Code Is Sent To You Check You Emails";
}
if(isset($_GET['id']) && isset($_GET['code']))
{
$id=$_GET['id'];
$code=$_GET['id'];
mysql_connect('localhost','root','');
mysql_select_db('sample');
$select=mysql_query("select email,password from verify where id='$id' and code='$code'");
if(mysql_num_rows($select)==1)
{
while($row=mysql_fetch_array($select))
{
$email=$row['email'];
$password=$row['password'];
}
$insert_user=mysql_query("insert into verified_user values('','$email','$password')");
$delete=mysql_query("delete from verify where id='$id' and code='$code'");
}
}
In your explanation you forgot the most important part: the random hash. Compare the hash, not the password. The guide explains it correctly.
The guide looks solid.
I would implement a better random password generator though, rand(1000,5000) is really not very good. You could even set up a first-time logon that asks for a password.
A warning: According to the PHP Manual, EREGI is DEPRECATED! http://php.net/manual/en/function.eregi.php
preg_match would be a good option. http://www.php.net/manual/en/function.preg-match.php

OOP PHP user class (usercake) not adding to database

I recently found this little user class script called usercake (http://usercake.com/), has all the basic functionality and seems to work very well.
My problem: The first user gets added to the database fine, but after that it is not working. Clearly there's just something slightly wrong that I'm not figuring out ( i do not know oop php very well). No errors occure (that i can see), and the email gets sent out.
I've installed it multiple places with the same fate. I'd like to fix it because using this script saves a lot of reinventing the wheel time.
Here is the URL where I have it: http://rawcomposition.com/birding/loggedin/register.php
Here is the function that gets called once everything is validated:
public function userCakeAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateActivationToken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userCakeMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array($websiteUrl,$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."Users` (
`Username`,
`Username_Clean`,
`Password`,
`Email`,
`ActivationToken`,
`LastActivationRequest`,
`LostPasswordRequest`,
`Active`,
`Group_ID`,
`SignUpDate`,
`LastSignIn`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
And here is the table structure:
CREATE TABLE IF NOT EXISTS `userCake_Users` (
`User_ID` int(11) NOT NULL AUTO_INCREMENT,
`Username` varchar(150) NOT NULL,
`Name` varchar(100) NOT NULL,
`Username_Clean` varchar(150) NOT NULL,
`Password` varchar(225) NOT NULL,
`Email` varchar(150) NOT NULL,
`ActivationToken` varchar(225) NOT NULL,
`LastActivationRequest` int(11) NOT NULL,
`LostPasswordRequest` int(1) NOT NULL DEFAULT '0',
`Active` int(1) NOT NULL,
`Group_ID` int(11) NOT NULL,
`SignUpDate` int(11) NOT NULL,
`LastSignIn` int(11) NOT NULL,
PRIMARY KEY (`User_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
To me, there are 2 possibilities why it is not adding further users after the first one is added:
First, $this->mail_failure flag is set to TRUE for the following user accounts after the first user is created. But this scenario is not likely because it is the same code that has run successfully for the first user and therefore there is no reason why the flag should be TRUE for others.
Second possibility is that $this->status is FALSE for the second user account. If false, the method userCakeAddUser() does not do anything. The reasons why this flag could be false is either the username or the email address already exists.
Are you using the same username or email address you used for the first account for the second account as well? I'm sure you must not be using the same username but perhaps the same email address. The usercake classes does not allow the same username or same email addresses.
Hope this helps.
I would do 4 things with this uggly code :
1) to enable the error_reporting mode so that you can see something in case sthg occurs :
error_reporting(E_ALL);
2) to test this INSERT sql straight into the dB to make sure it's working properly, and validate this piece of code. If the sql INSERT request is valid, then check the access conditions to these SQL request, like Abhay said above,
3) As we do not have your all config available, a guess game is difficult. So I'd suggest you to add one NULL field for the AI User_ID.
$sql = "INSERT INTO `".$db_table_prefix."Users` (
`User_ID`, // Add this here
`Username`,
`Username_Clean`,
`Password`,
`Email`,
`ActivationToken`,
`LastActivationRequest`,
`LostPasswordRequest`,
`Active`,
`Group_ID`,
`SignUpDate`,
`LastSignIn`
)
VALUES (
NULL, // and that one
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0', // later, I would also try using an int for an int
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
4) to find another one, better coded, using OOP and PDO.
You given Name as NOT NULL and in Insert statement of your code is not sending Name value, so mysql will throw an exception, saying Name cannot be null, check this once.

Categories