Just looking for advice on how to apply the urlencode into this bit of code. It is actually working, the issue when the email is received, the urlencode doesn't seem to work.
function reset_password($email) {
$query = "DELETE from reset_password where email = $email";
$deletepass = mysql_query($query);
$code = substr(base64_encode(crypt('', '')), 0, 32);
$query2 = "INSERT into reset_password values ($email, '$code', " . time() . ")";
$insertval = mysql_query($query2);
$f = "SELECT userEmail from gn_users where email = $email";
$from = "***"; // sender
$f['userEmail']; // recepient
$message =
"From: *** <***>\r\n" . // email headers
"To: {$f['userEmail']} <{$f['userEmail']}>\r\n" .
'Subject: Reset Password' . "\r\n" .
"\r\n" .
"Hello\r\n" . // email imap_body(imap_stream, msg_number)
"\r\n" .
"A request has been made to reset your example.com web site password.\r\n" .
"\r\n" .
"To complete the request, click on the following link within 48 hours of the transmision of this email and follow the on screen instructions.\r\n" .
"\r\n" .
"index.php?page=reset-password&email=" . urlencode($email) . "&code=" . urlencode($code) . "\r\n" .
"\r\n" .
"Kind regards,\r\n" .
"\r\n" .
"The example.com Web Site";
$to = "$email";
$subject = "Test mail";
$message = "$message";
$from = "***";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";}
I'll try to help you out with some tips to write one yourself, without having to rely on that awful code.
You need to break the task down in multiple, bite sized, easy to do tasks.
Here we go:
The user needs a page where to request a password reset. It's a form with an email field (and/or username).
We have the user email, and if it exists, we need to generate a reset password link that can't be guessed, so that not everyone can reset someones password.
So you need to generate a unique hash for this request, an option would be uniqid(), but there are many options here. So you generate a link that looks like: http://test.com/reset.php?uid=443&hash=33rr3344rree22. It can't really be guessed because you need to know both the user id and the has. But to make sure, we will make it expire in an hour or day.
Next, we ensure that this link will work. We have to create a table for password reset requests that contains the following columns: id, email, hash, date_added, and insert it (the date can be TIMESTAMP with a default of CURRENT_TIMESTAMP).
Now it's time to send the email. You can add any text you want, as long as you mention the url you generated a bit earlier.
Now the user clicks the link. You get the user id and hash, and check if such an entry exists. If it does, and the request is not older than 1 day, we generate a new password, update the users table, and send him a confirmation mail.
This is optional, but recommended. Create a cron job that clears the password reset request table for entries older than 1 day.
Each of these steps are fairly easy to do, or you can find a lot of information about them around the web. If you take your time to understand each step, sanitize everything properly, and do things by the book, you will learn a lot.
Related
I have a MySQL DB with EMAIL row.
User perform a search and the relevant info comes up in a <table> format (address 1, address 2, phone, fax, email, etc).
In the <tabel>, the last column has an "E-mail" button and if you click it the system should send an automated email to that email address.
I have found one article here which actually works for me, but it send email to everyone in the DB. How can I modify this php to send email to ONLY that specific row.
Here is what I found:
mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT email FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
sendMail($row[0]);
}
mysql_free_result($result);
function sendMail($to){
$subject = 'AC the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
What to add/replace to it to send email to individual row in DB TABLE?
when the email sent by this code to my gmail account i can see the sender is: "webmaster#example.com ip-XXX-XXX-XXX-XXX.yyyyyyyyyyy.zzzz.net" (which is my server's IP).... WHY does it appear like that???
I have added to this code the following to see if it picks up the right records (which it does):
mail($to, $subject, $message, $headers);
echo 'email has been sent to: ' . $to . '<br/>';
}
after email sent, it list the email addresses back to me and all email addresses receives the email...
I would appreciate your help!
1: What to add/replace to it to send email to individual row in DB TABLE?;
you can add conditional query to fetch particular user's email like :
SELECT email FROM mytable where <your condition>
2: when the email sent by this code to my gmail account i can see the sender is: "webmaster#example.com ip-XXX-XXX-XXX-XXX.yyyyyyyyyyy.zzzz.net" (which is my server's IP).... WHY does it appear like that???
by default it shows the server default email address, you can update it also. To do so, follow the link : Change outgoing mail address from root#servername - rackspace sendgrid postfix
So, I found this thread (Get all data from mysql row in a variable) but I am too much of a beginner to make it apply easily to my situation. Thank you for helping me out... sorry for the total newb questions.
I have a PHP form that lets the user select one of my tables in a database where email addresses are stored to send an email to each of them. Right now, I have this code:
$recipientid = $_POST['recipientid'];
$body = $_POST['body'];
$subject = $_POST['subject'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: SENDER NAME <senderemail#gmail.com>' . "\r\n";
date_default_timezone_set('America/Los_Angeles');
$time = date('m/d/Y h:i:s a', time());
$sendbody = $body . "<br><br>This is a bulk email announcement sent by
the institution.<br><br>It was sent at " . $time . ". If you have any
questions about this message or wish to unsubscribe, please contact
the institution.";
if($recipientid == 'allstudents'){
// SEE NOTE #2//
$recipientlist = //email addresses
}
$process=explode(",",$recipientlist);
reset($process);
foreach ($process as $to) {
$sent=mail($to,$subject,$sendbody,$headers);
}
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
What is the easiest way to capture all of the email addresses in the column of the specified table and then loop a mailto for each? I was originally trying to get them all into one string and then explode them as you can see, but that might not be the best solution. Am I on the right track here?
(NOTE #2 FROM IF)
HERE IS WHERE I NEED SOMETHING... I was sort of thinking about trying to use the following. I need it to grab all the emails from the column emailaddresses in the table students. I am using an if statement because there are four other things that $recipientid could equal, and each different one grabs email addresses from a different table.
array pg_fetch_all_columns ( resource $result [, int $column = 3 ] ) But then, I don't know how to get this array to work with my mail. I originally tried to use just a SELECT * from emailaddresses and then use each row somehow but I don't know how to implement that.
YES, I know I am using mysql not mysqli and I know that mailto is probably not the best solution, but it is what I have to work with right now (unless you can suggest an alternative route for the mail loop).
Thank you again! I really want to learn what I am doing, so an explanation would be appreciated:)
(and ps I am using the mail function with the explode because of this article http://tutorial.world.edu/web-development/php-script/how-to-send-out-mass-emails-php-script/)
I might be a little confused about the question. It sounds like you have a database with email address and you want to send an email for each email address. I think you can just do the query SELECT emailaddress from table and cycle through the results and use your mail function each time.
$query = *your select query*
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$sent=mail($row['emailadress'],$subject,$sendbody,$headers);
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
If you want your user to select the table the email addresses are coming from you can use a form and a variable in the query.
You can use the below piece of code to send the mail.
Consider you have an email field in your table 'students'
then
$sel = mysql_query("select email from students");
while($info = mysql_fetch_assoc($sel))
{
$to = $info['email'];
$sent=mail($to,$subject,$sendbody,$headers);
//---Remaining code goes on
}
try it.
I'm trying to do a password reset using mail, so what will happen is the user will enter his email on the forgot password and on button click it will be sent to the email that is on the database. Now what i will do is give the user a new random password and to do this the user should click on the link on the email to verify that he really wants to change the password, will that be possible? Here is my code
if (isset($_POST['mytxtmail']))
{
$newid = ($_POST['mytxtmail']);
$result = mysqli_query($con,"SELECT EMAIL FROM members WHERE EMAIL='$newid'");
if($result->num_rows == 0) {
echo 'Mail Successfully Sent to '.$newid;
return false;
}
else
$to = $newid;
$subject = 'the subject';
$message = 'Please Click here to Verify the Change of Password';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo 'Mail Successfully Sent to '.$newid;
}
It's a bit of a long procedure to write the full code here.
One way you can do is, make a new column in your users table, let's say pass_request_hash , now whenever the user clicks on forgot password option and enters his e-mail ID and submits, an update query runs to dump a random value into pass_request_hash for that user and at the same time a mail is sent with that same hash value and also his e-mail ID as GET parameters.
Now when the user has clicked on the link sent to him by e-mail, the link points to a PHP script which checks with the database if the hash and e-mail received from the GET parameter matches with those in the database, if yes then you can have another script getting executed to send a new password to that e-mail ID.
You can also set a timeout for that hash.
There are other ways to do it too, check out some of these tutorials:
One
Two
Three
You should include the link in the email which would take the user to the password verification script (it could be the same you are using here, only add needed functionality).
i have a registration form that allows users to register and become members on my site. So far once they register their details this goes in the database and they get an email sent out to say thanks.
I am trying to duplicate the script so that i can send a different email letting me know when a users registered and have this sent to my email.
I'm trying to do it this way because the email that gets sent out to the user contains a randomly generated md5 hash code that i also need to have sent to me in the email sent to me telling me they've registered.
I've managed to get the two emails to deliver to the correct email accounts. however, the email being sent to me letting me know a user has signed up is also being sent to the user and i don't want it to go to them?
Can anyone suggest where I'm going wrong? Thanks
CODE to send email to user:
<?php
/**
* ShuttleCMS - A basic CMS coded in PHP.
* code generator - Used for allowing a user to generate a code
*
* #author Dan <dan#danbriant.com>
* #version 0.0.1
* #package ShuttleCMS
*/
define('IN_SCRIPT', true);
// Start a session
session_start();
/*
* Generates new code and puts it on database
*/
//Generate a RANDOM MD5 Hash for a code
$random_code=md5(uniqid(rand()));
//Take the first 8 digits and use them as the password we intend to email the user
$emailcode=substr($random_code, 0, 8);
//Encrypt $emailpassword in MD5 format for the database
$registrationcode=($emailcode);
// Make a safe query
$query = sprintf("UPDATE `ptb_registrations` SET `registration_code` = '%s' WHERE email = \"$email\"",
mysql_real_escape_string($registrationcode));
mysql_query($query)or die('Could not update members: ' . mysql_error());
?>
<?php
$subjectconfirm = " Thanks for your Registration";
$headersconfirm = "To: $email\r\n";
$headersconfirm .= "From: siteindex.com <registrations#siteindex>\r\n";
$headersconfirm .= "Content-type: text/html\r\n";
$sep = sha1(date('r', time()));
$bodyconfirm = <<< EOF
(EMAIL BODY)
EOF;
// Finally, send the email
mail($email, $subjectconfirm, $bodyconfirm, $headersconfirm);
?>
Then i'm duplicating the code like this but replacing the to email address. and it sends to my email account fine but it sends both emails to the user and i don't want them getting the email intended for me.
Code to have email sent to me:
<?php
/**
* ShuttleCMS - A basic CMS coded in PHP.
* code generator - Used for allowing a user to generate a code
*
* #author Dan <dan#danbriant.com>
* #version 0.0.1
* #package ShuttleCMS
*/
define('IN_SCRIPT', true);
// Start a session
session_start();
/*
* Generates new code and puts it on database
*/
//Generate a RANDOM MD5 Hash for a code
$random_code=md5(uniqid(rand()));
//Take the first 8 digits and use them as the password we intend to email the user
$emailcode=substr($random_code, 0, 8);
//Encrypt $emailpassword in MD5 format for the database
$registrationcode=($emailcode);
// Make a safe query
$query = sprintf("UPDATE `ptb_registrations` SET `registration_code` = '%s' WHERE email = \"$email\"",
mysql_real_escape_string($registrationcode));
mysql_query($query)or die('Could not update members: ' . mysql_error());
?>
<?php
$subjectconfirm = " Thanks for your Registration";
$headersconfirm = "To: signups#siteindex.com\r\n";
$headersconfirm .= "From: siteindex.com <signups#siteindex>\r\n";
$headersconfirm .= "Content-type: text/html\r\n";
$sep = sha1(date('r', time()));
$bodyconfirm = <<< EOF
(DIFFERENT EMAIL BODY)
EOF;
// Finally, send the email
mail($email, $subjectconfirm, $bodyconfirm, $headersconfirm);
?>
You'll notice from the mail manual page, the first parameter is where the email is sent to. You haven't changed it. You have only changed the header. In order to send an email to someone else, change:
mail($email, $subjectconfirm, $bodyconfirm, $headersconfirm);
to:
mail('signups#siteindex.com', $subjectconfirm, $bodyconfirm, $headersconfirm);
Of course, it is far more sensible to just BCC it to yourself instead of duplicating all this code.
I don't see the need to duplicate the code. Just send two emails:
$emails = 'youremail#email.com, theiremail#email.com';
mail($emails, $subjectconfirm, $bodyconfirm, $headersconfirm);
Or BCC yourself:
$headersconfirm .= 'Bcc: youremail#email.com' . "\r\n";
Take a look here.
I am hoping that there is a standard class/php script that we can use for the "forgot password" functionality. It seems almost every website has one, and I'd like to reduce the development time on it.
It appears that a common approach is:
click on Forgot password
User receives via email a "reset password" link
Click on the link allows typing in "new password" "retype password"
life is good
I don't want to do it from scratch, hoping someone who has thought through any nuances can point me to pre-existing code. It would seem that this is a pretty standardized.
All: got some responses, but I'm hoping perhaps someone can recommend a pretty standard class or CMS that meets generally accepted security guidelines.
I use my own scripts for password resetting.
I create a table to store a user_id, a random key and a time that the password reset initiated:
// query is my own SQLite3 wrapper function which ensures I have a valid database connection then executes the SQL.
// I would imagine small changes will be needed to the SQL for MY SQL.
query("create table reset_password (user_id integer not null default 0, key text not null default '', time integer not null default 0)");
query("create unique index reset_password_user_id on reset_password (user_id)");
query("create index reset_password_key on reset_password (key)");
Then when a password needs to be reset, the following code is called:
// $user_id must be an integer that matches a valid user's ID.
function reset_password($user_id) {
query("delete from reset_password where user_id = $user_id");
$key = substr(base64_encode(crypt('', '')), 0, 32);
query("insert into reset_password values ($user_id, '$key', " . time() . ")");
// fetch is my own wrapper function to fetch a row from the query.
$f = fetch(query("select username from users where id = $user_id"));
// smtp is my own function, you will probably want to use the php mail function.
smtp(
"do-not-reply#example.com", // sender
$f['username'], // recepient
"From: The example.com Web Site <do-not-reply#example.com>\r\n" . // email headers
"To: {$f['username']} <{$f['username']}>\r\n" . // actual email address <put a nice friendly name in here if you have the the information>
'Subject: Reset Password' . "\r\n" .
"\r\n" .
"Hello\r\n" . // email body
"\r\n" .
"A request has been made to reset your example.com web site password.\r\n" .
"\r\n" .
"To complete the request, click on the following link within 48 hours of the transmision of this email and follow the on screen instructions.\r\n" .
"\r\n" .
/// URL is defined as the root of the URL used in the email, in this example it would be "http://example.com/"
URL . "index.php?page=reset-password&user_id=" . urlencode($user_id) . "&key=" . urlencode($key) . "\r\n" .
"\r\n" .
"Kind regards,\r\n" .
"\r\n" .
"The example.com Web Site"
);
}
When the link in the email is clicked a page is displayed which contains the following:
// form, input_hidden, table, tr, td, label, input_password and input_submit are my own wrappers which return the appropriate HTML with escaped values where required.
echo
form('reset-password/ok',
input_hidden('user_id', $_GET['user_id']) .
input_hidden('key', $_GET['key']) .
table(
tr(
td(label('New Password')) .
td(input_password('new_password', ''))
) .
tr(
td(label('Confirm Password')) .
td(input_password('confirm_password', ''))
)
) .
input_submit('ok', 'OK')
);
When the above form is submitted, the following is executed:
// The reset_password_message function displays the message to the user.
if (!isset($_POST['user_id'])) {
reset_password_message('You must enter a user ID. Please try again.');
} else if (!isset($_POST['key'])) {
reset_password_message('You must enter a key. Please try again.');
} else if (!isset($_POST['new_password']) || !$_POST['new_password']) {
reset_password_message('You must enter a new password. Please try again');
} else if (!isset($_POST['confirm_password']) || $_POST['new_password'] != $_POST['confirm_password']) {
reset_password_message('The new password and the confirmation do not match. Please try again.');
} else if (!$f = fetch(query("select time from reset_password where user_id = " . (integer)$_POST['user_id'] . " and key = '" . escape($_POST['key']) . "'"))) {
reset_password_message('The user ID and key pair are invalid. Please try again.');
} else if ($f['time'] < time() - 60 * 60 * 24 * 2) { // 60 seconds * 60 minutes * 24 hours * 2 days (48 hours as explained in the email sent to the user above).
reset_password_message('The user ID and key pair have expired. Please try again.');
} else {
query("update users set password = '" . crypt($_POST['new_password']) . "' where id = " . (integer)$_POST['user_id']);
reset_password_message('Your password has been reset. Please login.');
}
You're welcome to use this code instead of "rolling your own", but you will need to make a few changes or add a few functions to make it complete.
You can steal it from a wide variety of frameworks/CMSs. Drupal, Kohana, etc...