I've got email function setup and working by setting the code to email a specific email address. However, with this is that it goes to the same email address everytime the submit button is pressed based on the data entered in a text box who the mail comes from.
However, I want to change it so that when a user enters their username in the username box it checks my database table for that username and checks their email address and emails them all the information set for that user.
The code i'm using is ;
$username = $_POST['username'];
$my_query="SELECT * from loanusers where username = '$username'";
$result= mysqli_query($connection, $my_query);
$to = $myrow["emailaddess"];
$subject = 'CSG - Forgotten Password';
$sender = 'CSGLoanSystem#mail.com';
$password = $myrow["password"];
$admin = 'CSGLoanSystem Admin Team';
$body = <<< EMAIL
Hi {$username}, You have recently requested a notification of your password.
The Password registered with account {$username} is $password.
Thanks - {$admin}
EMAIL;
$header = "From:" . $sender;
if ($result):
mail($to, $subject, $body, $header);
$feedback = 'Email Sent';
endif;
At the moment when the submit button is pressed, the page refreshes but nothing actually happens and no email is received at the expected email address?
Pointing to the right direction:
Read up on MySQL and PDO. Also Read up on prepared statements and parameter binding.
Elaborating on the directions given:
There are many ways to connect to a database, and there are many different databases available. One popular database software is called MySQL, and the coding method that is most recommended to connect to that database is PDO for reasons such as having better methods for preventing security breaches.
You can find a lot of online tutorials on how to connect to a database, so I won't go into that, though I will however give you an example of a query you could use to do your email searching, and also I'll include prepared statements and parameter binding since these two details are often misunderstood by a lot of programmers.
If you have the following table:
users
______________________________
| username | email |
|------------+-----------------|
| john44 | abc#gmail.com |
|------------+-----------------|
| adam11 | 123#gmail.com |
|------------+-----------------|
the following code would allow you to retrieve john44's email:
$username = $_POST['username'];//getting the username written in the form
$sql = "SELECT email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//here I'm just outputting the obtained email for you to see
//it works, however you would then use the email saved in
//$result['email'] whichever way you want.
echo "email = {$result['email']}<br>";
Edited:
After you edited your code, I noticed you are not fetching the information you queried. Insert the following code after line $result= mysqli_query($connection, $my_query);:
$myrow = mysqli_fetch_assoc($result);
Related
I'm using this code as part of an email confirmation script. It works great, except I can't figure out a way to distinguish between when somebody has provided an invalid email address vs when they have simply refreshed the page (ie. already confirmed their account). The only think I can think of is putting a time stamp field in the users table that always gets updated, but I'm hoping there is a better way. I thought REPLACE would do the trick, but, while email is unique, it is not the primary key.
if (isset ($email, $token, $correctToken)){
$success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
if ($token == $correctToken) {
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE email = '$email'");
if (mysql_affected_rows() == 1) {
echo "Thank you! Your email address is confirmed and your account is actived.";
$success = TRUE;
}
}
if (!$success) {
echo "There was a problem with the confirmation. Try the link in your email again or contact us at Support#WiseRenters.com";
// Send email to admin to notify of error
exit;
}
}
Thanks in advance for the advice!
Billy
EDIT: The $email and $token variables are provided through $_GET or $_POST, in case that wasn't obvious.
A redirection would stop them from refreshing - but what if they click the link in their email again?
You should check if the current user is activated or not.
$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);
if( $conf ) {
// Redirect them to their profile with a message saying "your account has already been activated"
header("Location: /profile?already_activated");
exit;
}
// your code
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE id = '{$id}'");
In response to your comment:
Keep in mind this will only add an additional query for a user who has not activated yet. If they have activated then the redirect occurs and the page is still running only 1 query.
To optimize this a bit, you can select the user ID and confirmation status based on the email address. Then, if they do need to be activated, you can activate them based on user ID instead of email. Since an integer key is much faster, the combined time of the 2 queries will be about the same as the 1 query where you are updating based on a string column. I updated the code to reflect this.
Also, this page will probably not be accessed very frequently. Any optimizations from here would really be micro- and not really that helpful.
By the way I hope you are using mysql_real_escape_string on the email, and that conf is a boolean true/false not a string 'true'/'false'.
following is my script for send email inquiry.. the recipient email address was stored in a db called users.. this script will not work properly.. i think the problem is recipient email section.. because when i used a email address instead of $user it will work..
thanx help me
<?php
$refno = $HTTP_POST_VARS['refno'];
$proid = $HTTP_POST_VARS['proid'];
$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$msg = $HTTP_POST_VARS['msg'];
//connect db and find email address related to id
include 'db_connector.php';
$id=$HTTP_POST_VARS['id'];
$query=mysql_query("SELECT user_email FROM users WHERE id='".$id."'");
$cont=mysql_fetch_array($query);
$user=$cont['user_email'];
// recipient name
$recipientname = "'".$name."'";
// recipient email
$recipientemail = $user ;
// subject of the email sent to you
$subject = "Inquiry for your advertisement No. (".$refno.")";
// send an autoresponse to the user?
$autoresponse = "no";
// subject of autoresponse
$autosubject = "Thank you for your inquiry!";
// autoresponse message
$automessage = "Thank you for your inquiry.! We'll get back to you shortly.
";
// END OF NECESSARY MODIFICATIONS
$message = "reference number : $refno
$msg
From $name $email
---";
// send mail and print success message
mail($recipientemail,"$subject","$message","From: $recipientname <$email>");
if($autoresponse == "yes") {
$autosubject = stripslashes($autosubject);
$automessage = stripslashes($automessage);
mail($email,"$autosubject","$automessage","From: $recipientname <$recipientemail>");
}
header("Location:index.php");
exit;
?>
First of all, your query is SQL injectable. Never ever pass a variable coming from a POST request directly into an SQL query. Use mysql_real_escape().
As to your bug: it seems that $user does not contain a valid e-mail address. so, the Mysql query is not returning an e-mail address.
Use $_POST rather than $HTTP_POST_VARS.
Switch on error reporting by prepending these two lines to your PHP code:
PHP code:
error_reporting(E_ALL);
ini_set('display_errors','1');
Run your script again. Do you get any notices or warnings?
If not, try to display your query, by adding
die($query);
just before the line that has the mysql_query command, and then run the query manually (e.g. using PhpMyAdmin or MySQL Query Browser) to see if you are actually getting a result that looks like an e-mail address.
Debug your PHP program.
Check out :
If the variables contain the supposed values.
Query is okay and returns result.
Proper header is set with mail function.
etc.
PHP manual have a good example to send mail.
Do not use $HTTP_POST_VARS['name']; it is deprecated use $_POST instead.
hey guys thanx for the help.. i found the error done in my inquiry form.. the id filed hidden outside of the form tag.. therefore the id value will not passed to the sendinq.php. i change it thank now the sendmail option work properly
I'm trying to create a forgotten password form that emails users their password. I'm having a problem, though, with the actual password part. You see, I have the email and comparing the email correct, except whenever I send the email I always get either "Your password is ." or "Your password is Array". I'm using:
$check_email = mysql_num_rows(mysql_query("SELECT email FROM userRecovery WHERE email = '$to'"));
if($check_email == 1){
$qtip = mysql_query("SELECT password FROM userRecovery WHERE email = '$to'");
$theirPassword = mysql_fetch_array($qtip);
Rest of the Code...
}
I used to be able to do this correctly, but I haven't done PHP or MySQL in too long so it's slightly annoying (that, and I'm at a beginner-intermediate kind of level). I remember having this exact problem, but I don't have the code with me to find out what I did. If you think I left out a detail, please say so.
Any help if appreciated.
$theirPassword, as you're using it, is an array (as what's being fetched via your mysql_fetch_array command). Try either $theirPassword['password'] or use just `mysql_result($qtip,'password')``
mysql_fetch_array returns an array, so if you're using your $theirPassword it will contain an array. Since you're selecting password from your query, you likely need:
$qtip = mysql_query("SELECT password FROM userRecovery WHERE email = '$to'");
$row = mysql_fetch_array($qtip);
$theirPassword = $row['password'];
What about fetching the email address and the password in one query? SELECT email,password FROM userRecovery WHERE email = '$to'. Then you can get the password just like in the previous 2 answers ($theirPassword['password']).
On top of that you may find this blog post about storing passwords in a db useful - http://blog.moertel.com/articles/2006/12/15/never-store-passwords-in-a-database
$sql = "SELECT password FROM userRecovery WHERE email = '$to'";
$password = mysql_result(mysql_query($sql), 0);
How can I ensure my login script is secure and make it better, This is my first code:
Help is most appreciated.
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, lastname, email, mobile, username, password)
VALUES('$firstname', '$lastname','$email', '$mobile','$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
header("Location: /registration?registration=true");
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
Follow Artefacto's advice about SQL injection and Hashing passwords in the database. Other things ...
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
Wont work because you can't echo then send a header. Headers must be sent before any output.
Also, there is no point doing this:
header("Location: /registration?registration=false");
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
The webbrowser will redirect straight away and the user won't see the handy message you've printed.
Also, it's usual to ask for 2 password fields on registration forms incase the user made a typo and didn't notice because all the text was *'s. You compare the 2 and if they are different you assume a typo was made and ask again.
That's not a login script. It's a registration script.
See SQL injection in the PHP manual. Your program is vulnerable to this kind of attacks.
Also, don't just or die(mysql_error()). This will expose information about your database that you may not want to expose (table names, etc.). Use proper error handling. For instance, you can throw an exception and define a uncaught exception handler that shows a "oops" page and logs the error.
Finally, use hashes strong than MD5, such as sha1.
As said by #Artefacto, that's not a login script.
But if you intend to do a login script I would like to give you a suggestion. I've done this a while ago.
Instead of doing something like this:
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
I would do this:
$sql = "SELECT * FROM users WHERE username = '$username'";
$user = //use the php-sql (query, fetch_row) commands to fetch the user row.
if (strcmp($user['password'], $password) == 0) {
//log in success
}
By doing this, you avoid SQL Injection in a simple and elegant way. What you guys think about it?
To reiterate what everyone else mentioned. It's important to protect yourself (and sever) from SQL injection. For example:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
You're just simple taking the value from $_POST['username'] and placing it in the variable $username.
Some people aren't very nice and will try to break your program :( So it's always recommended to escape any data that was taken from a user, before placing it into an SQL query.
For instance...
This:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
Becomes:
$checkuser = mysql_query("SELECT username FROM users WHERE username='" .mysql_real_escape_string($username). "'");
I use the following code to register users on my site. The problem is that when a user registers apache doesn't respond and crashes.
Is there a break in my code or something I am doing wrong????
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
//include 'register.html';
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, email, username, password)
VALUES('$firstname', '$email', '$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
this script will NOT cause apache to die. on this side theres nothing wrong with it.
however i dont know whats in db_connect.php
the mailing is deactivated, this indeed could take a very long time if the server settings are not correctly. e.g. if the server cant find its fully qualified domain name as your comments suggests.
do you have a session active? this could explain why you cant access any website while the other one is still running and sending the mail and it may look to you like apache crashed.
because you didnt call session_write_close and only once session can be active for writing at a time.
whats definately wrong is the vulnerability to mysql injection.
you absolutely need to change your variables the following way:
$firstname = mysql_real_escape_string($_POST['firstname']);
$email = mysql_real_escape_string($_POST['email']);
$username = mysql_real_escape_string($_POST['username']);
furthermore i would recommend just having a unique que on username and try the insert and see whether you get an error or if you get an mysq_insert_id. let mysql do the job.
but your check is fine too.. but you should have a constraint in the database too, just as a precaution.
and you should trim your values and maby allow only certain chars, its annoying if a username on a website is &%DTRFG$Ä←↓ff