How Do I Create a Account Email Confirmation in Php? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to send the user an email with a link (like many sites do) and when they click this link, their account will be activated. How exactly would I do this in Php?

I would do it this way:
1) Upon completion of registration, flag account as inactive (pending confirmation), and create two strings of random characters.
2) Store both strings in the database and associate them with the user.
3) Email a link to the user that has a link back to a page on your site and contains both strings.
Ex: www.mysite.com/confirm.php?auth1=j0832r2&auth2=fji4j32ion
4) Have your page check that both codes match, and if so, flag the account as active.
Hope this helps.

Here's the section of code that I use to send verification emails.
//create login hash
$hash = hash('whirlpool', $user->authentication->password . time() . $user->authentication->salt);
if( !Quick_Login::add($hash, $user->userid, time() + 3600, 0) )
{
// die
}
//load email template
ob_start();
include('templates/account_create.html');
$body = ob_get_clean();
if( Mail::sendMail($user->contact->email, 'no-reply-automator#domain.com', "Email Verification", $body) )
{
//redirect to login
throw new RedirectBrowserException("/index.php?code=6");
}
The Mail class is a simple mailer that I built, you can easily just use the php mail() function.
The email template that's loaded here is this:
<html>
<body>
<div style="width: 600px; border: 2px solid #E9EBF6; margin: auto; font-size: 16px; color: #555555;">
<h1 style="margin: 0; padding: 8px; background-color: #E9EBF6; text-align: center;">
Hello, <?=$user->fname;?>!
</h1>
<div style="overflow: hidden; padding: 8px; padding-top: 0; background-color: #F5F6FB;">
<p>You are receiving this email because you (or someone pretending to be you!) has signed up for a new account on the Domain System.</p>
<p>If you would like to verify this email account (and you must in order to use the system), please click this link.</p>
<p>If you don't know what this is about, or you don't want the account, simply do nothing.</p>
<p>The quick login link above is a one-time access pass to your account. Please use the link to verify your email address and complete your account signup.</p>
<br />
<p>Thanks!</p>
<p>-Domain</p>
</div>
</div>
</body>
</html>
The link they click in there goes to this script (verify.php):
<?php
set_include_path('../../backbone:../../global:../../jquery:../../components:../../content:../../images:../../model:../../render:../../scripts:../../styles');
require_once('RedirectBrowserException.php');
require_once('User.php');
require_once('Session.php');
require_once('Quick_Login.php');
setSession(0, '/');
$code = isset($_GET['code']) ? $_GET['code'] : null;
if( $code )
{
$ql = Quick_Login::getByHash($code);
if( $ql )
{
$user = User::getByID($ql->userid);
$user->disabled = 0;
$user->save();
setSessionVar('active', true);
setSessionVar('roleid', $user->authentication->role->roleid);
setSessionVar('userid', $user->userid);
$ql->used = 1;
$ql->save();
throw new RedirectBrowserException("/home.php?code=0");
}
else
{
throw new RedirectBrowserException('/index.php?code=9');
}
}
else
{
throw new RedirectBrowserException('/index.php?code=9');
}
?>
You'll see in that last script that it sets disabled=0 on their account, as well as logging them in (setting active on their session, and assigning their roleid and userid on the session).
Hope this helps.
Update
This is what's happening under the hood without all the code.
A random string of characters is created (preferably one that is not randomly guessable)
That string is stored in the database, with a link to the user's ID
An email is sent to the user containing a link to a script and the hash (e.g., verify.php?code=sdflnsdlknsge98y32598swob)
When the user clicks the link, the script handling it checks the database for that string (sdflnsdlknsge98y32598swob). If it's valid, it sets a flag on the user's account that indicates that they have validated their email address.
[OPTIONAL] The script can also log the user in automatically when they verify their email address.

I do the following.
Collect their email address and password
Store their password as a protected hash. I'm using PHP 7 so I use
password_hash($user_password, PASSWORD_DEFAULT);
Create and store a unique confirmation ID. I'm anal and paranoid, so I create long strings. In this case, 64 characters (32 bytes, bin2hex = 64 characters).
$confirm_code = bin2hex(random_bytes(32));
Email the user the confirmation link built using $confirm_code.
When the user clicks the link, set a database flag (e.g., "active_user") to indicate confirmation is complete. I do not delete the confirmation code.
OK, remember that I'm anal and paranoid. The backend does not delete the confirmation code and every new confirmation code is checked against all previous confirmation codes to ensure it really is unique. Why? So people can't happenstantially use their email link at a later date to confirm an account that isn't actually theirs and to guarantee no one gets a confirmation code that was issued to but possibly not used by someone else. (Remember, nothing is ever actually "unique" or "random" in the world of computers. If you don't check, you don't know.)
Also, you should NEVER automatically log someone in from their confirmation link. That's a huge security violation. Anyone could click the link before activation and suddenly they have full access to the account. Always force users to log in after confirmation.

The way that I have done it many times is during registration, Keep a field in the members table of "Active" being a bool (0 or 1) 0 being no, 1 being yes. During registration mark them as a 0. Also you will need a field of registration code. Or you can create a new table of userid/registration code and compare it.
When the user registered, create a unique code. Log that code and send them an email. when they click on the link in the email, check against the table with the code and if it matches a code in the db, change the active field for that user to 1

When they register, add a unique ID to the database for their username. Also have an "active" column set to 0. To send them an email, use the PHP mail() function. Have a link in the email linking to yoursite.com/activate?id=uniqueid. Fetch the ID on activate.php, do some checks, and set the "active" column in the database to 1.

Related

A secure enough way of identifying and activating a user in MySQL PHP with a URL

Is checking against my table with the user's email and dedicated hash enough to verify and activate an account if a match is found against those two values?
A user is asked to register themselves with user data and their email id. They are then sent a URL to their email which they are asked to click on to confirm and activate their account.
This is my current setup:
<?php //The user-account-creation processing page
$email_id = taken from user input;
$randomnessWhateverItsCalled = "lots-of-randomness-here";
UPDATE advert SET advert_hash = SHA1(CONCAT($email_id, $randomnessWhateverItsCalled))
//For simplicity's sake I omitted the PDO stuff
INSERT INTO table_name (..., user_email, hash, account_activated, ...) VALUES (..., usersEmail, advert_hash, NO, ...)
/**
Send an email with some php code with the URL that would look like this
URL to click on attached to email body:
*/
$attachStringToEmailBody = "http://www.domainname.com/activate-user?email_id=" . $usersEmail . "&hash=" . $randomnessWhateverItsCalled;
enter code here
//Send email from this process page with a little email php code
//Redirect user to a page informing the user to activate the account by visiting their email and clicking on the url
?>
Then in the activate-user.php page I have the following:
<?ph
$user_email = $_GET['email_id'];
$hash = $_GET['hash'];
/**
search database and return a row if there is a match containing both the $user_email and the $hash
if(match){
Update database and set the `account_activated` column to `YES`
}
else{
//Tell if there was no match then activation failed
//Let the user know that we do not recognise the link they used to try and activate their account.
}
*/
?>
It seems secure enough, as long as you made the "randomness" part hard to guess. You can put there the email, username, password, etc. and mix them up with another key - all encrypted - that's what I usually do.
But I would advise you to use 0/1 for active/inactive - why using strings, when you can do the same with smallint (1) - and save some space, thus making the database a bit lighter ?

"Issue viewing email? View email online?" unique link in Codeigniter email

I'm not sure where to begin with this task, so I'm looking for an answer on just the idea of how to go about doing this.
When a new user creates an account on my Codeigniter site I send him/her an email about signing up (very typical). Here is how I'm sending the email...
...
$subject = 'Welcome to __________, ' . $firstName . '!';
$emailData = array(
'name' => $name,
'blah' => $blah,
'blah' => $blah,
// etc.
);
$html_email = $this->load->view('emails/signup_html_view', $emailData, true);
$text_email = $this->load->view('emails/signup_text_view', $emailData, true);
$this->email->from('team#_________.com', '________ Team');
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($html_email);
$this->email->set_alt_message($text_email);
$this->email->send();
...
As you can see, I'm passing data to those views to send the email. In the email view, at the top, I have a link that says "Problem viewing email? Click here to view it online.". That is common practice for emails on newsletters, signups emails, etc. so that the user can view the email online if it renders weird or something goes wrong.
Where I'm getting lost is how do I generate that unique "...view it online." link so that when the user clicks it, they see an online version of the email and the online version still has all the data still passed to it? Do I need to create a separate controller or what is the best way to handle that? How do I generate that unique link?
#zach,
yes, what you do is:
1) create a separate controller that can display this email, just like you were making a page
2) I'm assuming the user is already created in the db, but is not yet activated or taken steps to be able to login. So, backing up a bit, when you make your user record, also create a random hashtag & store that.
Now, in the email link, set it to www.mysite.com/welcome/hashtag
This way you are allowing them to get a unique record without using an id that they could just use to go look at everyone else
This welcome page, of course, doesn't require them to be logged in. Probably you give them a submit (maybe after they fill out some more info) that will then activate their account
Hope that was close enough to what you were asking to get you through

how to delete mysql table row from mail inbox

I want to delete mysql table row from mail inbox , Is it possible !, If yes how can i delete the table row in my server database from any mail inbox account, please tell me the solution
Table Structure:
id usrname password status usercat
1 xxxxxxx xxxxxxx new 1
2 uuuuuuu uuuuuuu new 5
$del_qry= mysql_query("DELETE FROM table_name WHERE some_column=some_value")
In my site after Registration, the registered person get alert mail and also site admin get registered user detail's mail. So if the admin want to delete the second user(username - uuuuuu) from his mail account.
How can i do this, Please tell me i am new here...
The email you send to the admin will have to contain a link like this:
http://www.example.org/admin/remove_account.php?id=123
Where 123 is the user that was registered and remove_account.php is the script that will be loaded when the link is clicked.
Within the script you would have something like this:
mysql_query("DELETE FROM table_name WHERE id=" . mysql_real_escape_string($_GET['id']));
CAUTION
A few words of caution. The above link should be protected by one of the following:
User & password protection (either using Apache or PHP)
Signature protection (example below)
The signature protection prevents tampering / forging link parameters by adding a signature. Works like this:
$secret = "some reasonably long string of random data";
$id = "123"; // like above, the user id
$sig = hash_hmac('sha1', $id, $secret);
$link = 'http://www.example.org/admin/remove_account.php?' . http_build_query(array(
'id' => $id,
'sig' => $sig,
));
To verify the signature:
$secret = "some reasonably long string of random data";
if (isset($_GET['id'], $_GET['sig'])) {
$calc_sig = hash_hmac('sha1', $_GET['id'], $secret);
if ($calc_sig === $_GET['sig']) {
// your delete query here
}
}
Please note that, although the link protects against someone trying to access your administrative script, if it falls in the wrong hands you're still pretty much screwed. Don't underestimate security :)
I think you must add a link of a page of your site in email of delete with respect of user list. and when user click on link it will redirect to particular page where it will get that user id from url of link and then you can perform delete action. It is necessary to redirect to site page from mail because in mail you can not direct connect with database.
thanks

How to set up a mailing list site manager to bulk send newsletter to customers

I have a mailing list form to sign up to a mailing list and input the details into the database. But now I want an admin section where the user can create an email within the website and send it to all the people that have signed up to the mailing list. How can I do this?
Here is my code for originally creating the mailing list:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn2 = DB2();
require_once('header.php');
/*
* should we proceed with the form (if page is not submitted to itself echo the form)
*/
if (isset($_POST['submit'])) {
//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";
if (!isset($_POST['full_name']) || $_POST['full_name'] == "") {
$errors = true;
echo "<p style='color: red; position: absolute; top:115.5em; right:28em;'>Enter your full name</p>";
}
if (!isset($_POST['email']) || $_POST['email'] == "") {
$errors = true;
echo "<p style='color: red; position: absolute; top:120.1em; right:25.7em;'>Enter an email</p>";
}
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT(email) FROM maillist WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($count);
while($stmt->fetch()){}
if(!empty($count)){
echo "<p class='red'>Email already registered, please enter an alternative email</p>";
}
else
//if we have no errors, do the SQL
if (!$errors) {
$full_name = $_POST['full_name'];
$full_name = ucfirst($full_name);
//insert data
$stmt = $conn2->prepare("INSERT INTO maillist (billing_name, email) VALUES (?, ?)");
//bind the parameters
$stmt->bind_param('ss', $full_name, $email);
// Execute query
$stmt->execute();
//if the query worked, put out the confirmation message (you can make this look however you want)
if ($stmt) {
echo "<p class='black'>Thank you for joining out mailing list</p>";
//put out the footer and then stop the rest of the script from running, so we don't display the rest of the form (this is after the form has been submitted)
require_once('footer.php');
exit;
}
}
}
Admin Control Panel (ACP) aka Backoffice can be written with php easily.
You can create a new file or folder which will follow the next "logic":
1.Is the member logged-in and has permissions for ACP? (sessions/cookies)
2.If not , print the login form and check for his details.
2.1 If those details exists in your DB admin table - create a cookie or session.
3.If logged in show him the ACP.
There will be an option for the admin to write an email and send it to all of your subscribers. (according to your needs).
So you need to have a simple form with 2 fields: Subject and message (content).
When you submit the form , it will run a php script that will do:
1.Get the data of the form ($_POST['title'] for example)
2.Fetch all the subscribers from the database with a loop (while)
3.And while fetching them , send them an email with the mail function.
Why reinvent the wheel. There are several great services that already do this. They all have an api/functionality that you can use to build your subscriber lists. Plus, you get great reporting and click/link tracking and stats. Creating this functionality yourself would take a lot of effort.
Personally I use use Campaign Monitor - http://www.campaignmonitor.com/. It's rock solid, we've used it to send campaigns of 800,000 emails before :)
Here are the php code examples which enable you to manage list and subscribers:
https://github.com/campaignmonitor/createsend-php
You'd use an external mailing list manager, and send the message to the list address. The external MLM is configured to forward only mail from the web host, and divert everything else to the mailing list administrator. Be sure to test that noone but you can post to the list.
Reinventing the wheel, in PHP nonetheless, is only going to lead to pain, suffering and, in the case of mailing lists, public humiliation. There are just too many things to consider here, for example bounce handling (when an email cannot be delivered, you might want to react and update your database), so stick with an established solution.

Three rather than Four step forgot password functionality

I am using the EZ Publish CMS:
What is currently happening:
From the forgot password page, user enters the email address that they
used to register and submits
User receives an email with a password generating link which
uses a hash to confirm their identity.
User receives an email with a freshly generated password
User returns to site using the link from their email which takes them
to a form that asks for the old password (which was just generated
and has been sent to their email) and for them to enter a new
password.
What I want to happen:
From the "forgot password" page, user enters the email address that they
used to register and submits
User receives an email with a link to the "enter new password" form
On the "enter new password" form, user is not required to enter old
password because identity has already been confirmed by hash and
therefore only has to enter the new password.
I am using the EZMBPAEX extension which has the original 4 step process.
There doesn't seem to be any documentation or discussion about removing the "email the user a new password" step but my client has a very strict no passwords sent by email policy so I can't flex on this.
Does anyone know where I can find documentation on how to edit this functionality?
I think the file that will need to be edited is located in:
/extension/ezmbpaex/modules/userpaex/forgotpassword.php
First of All create a function to generate a random string for you, let's say you need to create a random string of 32 caracters, choose any number of caracters you want
Function to generate random code which will be sent by email and added to db
function genRandomString() {
$length = 32;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, (strlen($characters))-1)];
}
return $string;
}
Next, create a new table using php myAdmin, a table names forgotten_passes which contain three columns, let's say you already did that
$key = genRandomString(); // assign random code
$assign = $db->query("INSERT INTO `YOUR_DB_NAME`.`forgotten_pass` (`email` ,`randomKey` , `time`)
VALUES ('$email', '$key', CURRENT_TIMESTAMP );");
Next send an email which contain a link to your resetpassword.php page ( the page where user asked to choose a new password and confirm it, but do not forget to assign the generated key to a get variable , that's easy, just when you the link
www.yourdomain.com/pass_reset.php ( ADD ?secretkey=THE_GENERATED_HERE )
so the link sent to the email adresse of the person who need to reset the password should contain something like :
Hello username, to reset your password click on the link below or copy/past it into your browser
The link : http://www.yourdomain.com/pass_reset.php?secretKey=a12s236d5c8d4fkejus10a1s2d4c8741
When user click on the link, he will go to a page which verify his email and its corresponding random key in sql database, if it found that there are really an email and that random kay, then the user is really confirmed it's email, so this page should contain something like below :
<?php
if (isset($_GET['secretKey'])) {
$secretKey = $_GET['secretKey'];
// Check wether it really exist in database
$sql = 'select * from forgotten_pass WHERE email=$The_User_Email and randomKey='$secretKey'';
}
Now, just count the number of rows to see if there are returned data, if there are returned data than the user really connected to its inbox and clicked the link.
Just do the following :
if mysql_num_rows($sql)>0 { echo "Success, ";
?>
// in this part type the html code which displays two inputs text, password
// and confirm password that connect to database and update the user's password
<form method="post" action="passupdate.php">
<input name="password" value =""/>
<input name"confirmedPassword" value=""/>
<input type="submit" value="Save my new password">
</form>
<?php
} else {
echo "Sorry, invalid reset link";
}
When I updated the plugin it had the number of steps I wanted.

Categories