Sending a mail using PHP - php

I have a piece of code which upon approval sends a mail to an email address. The email is not being sent. Do I need to configure something on my web server?
function mailpassword($email, $password){
//notify that the password has been changed
mysqli_select_db($connect,"members");
$query = "select email from users where email = '".$email."'";
$mailquery = mysqli_query($connect,$query);
if(!$mailquery)
{
throw new Exception ('The entered email address could not be found');
}
else if($mailquery->num_rows==0)
{
throw new Exception ('The entered email address could not be found');
//username not in database
}
//if no errors, send mail
else
{
$row = $mailquery->fetch_object();
$email = $row->email;
$from = "From : support#example.com \r\n";
$mesg = "Hey,\n\n You requested for a new password. We have generated a completely random password for you, use it to login.\n\n
New Password - ".$password."\r\n
Please change this random password to a password of your choice once you log in. To change your password, click on the Accounts tab present in your dashboard.\r\n
Cheers\r\n
Hap";
if(mail($email, 'Password Change Account Details', $mesg, $from))
{
return true;
echo "great";
}
else
{
echo "Something went wrong";
}
}
$mails = mailpassword();
}

There's an easy solution to email problems: use a hosted solution that makes sure all email sent from your application gets through. There are some alternatives like Amazon and Postmark. We use Postmark with great success (not affiliated though ehe;)
There's this PHP class for Postmark that I'm kinda proud of... :-)
This wasn't directly an answer to your question, but I hope it was helpful anyway!

Try to remove the space before the colon in the From header:
$from = "From: support#example.com \r\n"

Related

Why is the else statement not working inside a foreach loop in php?

I'm building a script that helps a user reset their password if they forgot it. This specific script firstly checks if the email the user wants the token sent to exists. If it does, the token is inserted into a tokens table.
I am still developing and testing, so I haven't created the mail function yet.
I have an if statement that checks if the email exists, then creates the token. If it doesn't exists, it shows the page to enter an email address again. The if statement is working perfect, but the else is not. I'm pasting the entire file here, though it is only the part with the foreach statement that concerns our problem.
The else statement shows absolutely nothing.
<?php
//generate tokens to verify users who forgot their passwords. Send these tokens to the user's email
require $_SERVER['DOCUMENT_ROOT'] . "/phonebook/config.php";
//get user's email
$mail = htmlspecialchars($_POST['email']);
//generate token
$token = $token = openssl_random_pseudo_bytes(20);
//Convert the binary data into something more readable
$token = bin2hex($token);
//check if the email entered exists
$check = $conn->prepare("SELECT email FROM users WHERE email = :email");
$check->bindParam(":email", $mail);
$check->execute();
foreach ($check as $confirm) {
if ($confirm['email'] == $mail) {
//send tokens to the database
$sql = $conn->prepare("INSERT INTO tokens (email, token)
VALUES(:email, :token)");
$sql->bindParam(":email", $mail);
$sql->bindParam(":token", $token);
$sql->execute();
echo "<h2>Enter security code</h2>
A security code has been sent to the email addres $mail. Enter that code in the box below:
<form action = 'http://localhost/phonebook/controls/forgotpassword.php' method = 'post'>
<input type = 'hidden' name = 'email' value = '$mail'>
<input type = 'text' name = 'token'> <br>
<input type = 'submit' value = 'Reset password'>
</form>
Did not receive code? Go <a href = 'http://localhost/pages/forgotpassword.php'here</a>";
} else {
echo "That email does not exist. Please try again.";
include_once "$paste/phonebook/pages/forgotpassword.php";
}
}
Spotting three problems here.
You compare $mail which is encoded using htmlspecialchars() against an email address which is probably not encoded.
You fetch several rows instead of one:
//check if the email entered exists
$check = $conn->prepare("SELECT email FROM users WHERE email = :email LIMIT 1");
$check->bindParam(":email", $mail);
$check->execute();
$confirm = $check->fetch()
if (isset($confirm['email']) && $confirm['email'] === $mail) {
//send tokens to the database
You tell the "user" that the email address does exist in your system; this is a privacy and data security concern. Just send something like "If the entered email address is in our system, we just sent a password reset link to it."

Php/sqli executed by referencing the link in a send email function?

So i have this page called unsubscribe_process which when given a url query, e.g. www.example.com/unsubscribe_process.php?passkey=123, it will then find and delete the member using mysqli.
The problem I am having is with my unsubscribe.php page. It includes a form and allows the user to put in their email. The form will be submitted, and then an email is sent to the user linking the unsubscribe_process.php page with the specific query and passkey for that user. The hope would be then the user checks their email and clicks the link and then the unsubscribe_process page would remove them from the database.
Back to subscribe.php page, it has no DELETE slqi function anywhere in it, however somehow the user gets deleted after submitted the form. It seems to execute the www.example.com/unsubscribe_process.php?passkey=123 within subscribe.php, without the user having to click on it in the email.
Here is the function that is executed once a user submits their email:
function sendEmail() {
//enter details into db automatically
$con = #require './../dbcon.php';
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$email = mysqli_real_escape_string($dbConnection, $_POST['email']);
$atIndex = strrpos($email, "#");
$emailindex = substr($email, 0, $atIndex);
if ($email=='')
{
echo "<p>No Username has been specified. Please <a href=http://www.example.com/unsubscribe.php> try again.</a></p>";
}
//check if username exists in database
$result = mysqli_query($DB,"SELECT * FROM members WHERE user='". $emailindex ."'") or die(mysql_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$passkey = $row['confirmcode'];
//if password is set then erase password and send an email to user to update details/create new password.
if ($row['paid'] ==1){
$to=$email;
$subject="Unsubscribe";
$header="from: webmaster#example.com";
$message.="You can now unsubscribe yourself in one click with the following link: \r\n";
$message.="http://www.example.com/unsubscribe_process.php?passkey=$passkey\r\n\r\n";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail){
echo "</br><p class='maintextSubmit' align='center'> Please check your email to complete the process.</p>";
}
else echo "</br><p class='maintextError' align='center'> An error occurred. Please try again.</p>";
}
mysqli_close($DB);
}
}
}
SO: Does php execute the link for me when sending the email? This is literally the only reference to the unsubscribe_process.php page anywhere on the subscribe.php page. Why does the unsubscribe_process.php?passkey=$passkey get executed when the email is sent? How can I prevent this from happening (aka only when the link is clicked via the email)? Am I missing something?

what to do with this error?

I have had my script running on a localhost WampServer 1st which where it worked and then exported it to my online live domain.
After some adjustments i got the script partically working again but i am still getting below error
Call to undefined function filter_var()
The purpose of this script is when an user wants to registrate it will validate the email address and add the user to the database and send an validation link to the users emailaddress.
Here is the script:
<?PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
// connection towards database with a include function
include ('connection.php');
if (isset($_REQUEST['send']))
{
if(isset($_REQUEST['NAAM']))
{
$naam = $_REQUEST['NAAM'];
}
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}else
{
return FALSE;
}
}
//if "email" is filled out, proceed
if (isset($_REQUEST['mail']))
{
//check if the email address is invalid
$mailCheck = spamcheck($_REQUEST['mail']);
if ($mailCheck == TRUE)
{
$email = $_REQUEST['mail'];
}else
{
$mailCheck = FALSE;
echo "Invalid input email";
}
}
if(isset($_REQUEST['question']))
{
$quest = $_REQUEST['question'];
// checks if the filled in Question is de same as the answer novice or Novice
if ($quest =="novice" or $quest =="Novice")
{
$questCheck = TRUE;
}else
{
$questCheck = FALSE;
echo "Your answer to the question was incorrect!<br>";
}
}
if(isset($_REQUEST['wachtwoord'] , $_REQUEST['c_wachtwoord']))
{
$WW = $_REQUEST['wachtwoord'];
$c_WW = $_REQUEST['c_wachtwoord'];
// checks if the filled in password is de same as the confirmation password
if ($WW == $c_WW)
{
$pwCheck = TRUE;
}else
{
$pwCheck = FALSE;
echo "Your filled in passwords are not the same try again!<BR>";
}
}
// checks if both password confirmation and question are TRUE continue else retrieve fault
if ($pwCheck && $questCheck && $mailCheck == TRUE)
{
$hash = md5( rand(0,1000) );
// insert all filled in values into the database
$opdracht1 = "INSERT INTO users (ID , name , password , mail , staffLevel , hash , active) VALUES ('','$naam','$WW','$email','0','$hash','0')";
// run query
if (mysql_query ($opdracht1))
{
header( "refresh:5;url=http://www.debeerislos.nl/inlog_user.php" );
echo "Your account has succesfully been created! Please check your email to validate your account!<BR>";
$to = $email; //Send email to our user
$subject = 'Signup | Verification'; //// Give the email a subject
$message = '
Thanks for signing up!
Your account has been created!
You can login with the following credentials:
------------------------
Username: '.$naam.'
Password: '.$WW.'
------------------------
After you have activated your account you will have the rights so you can fully use it.
Please click this link to activate your account:
http://www.debeerislos.nl/verify_user.php?email='.$email.'&hash='.$hash.'&name='.$naam.'
'; // Our message above including the link
$headers = 'From:info#debeerislos.nl' . "\r\n"; // Set from headers
mail($to, $subject, $message, $headers); // Send the email
}else
{
echo "Woops something went wrong please contact the Administrator of the website or fill in the form again!<br> <A href='http://www.debeerislos.nl/form_register_user.html'>CLICK HERE!</A> to fill in the forum again";
}
}elseif ($pwCheck && $questCheck == FALSE)
{
echo "you filled both the password confirmation and the answer to the question incorrect!<br>";
}
}else
{
echo "Either you haven't send anything! or you haven't filled in the form<br>";
}
?>
In advance thank you.
Kind Regards,
StaleDevil
where have you defined filter_var() function? It is not defined in your given code. If you are defining it in the same page then how are you defining? provide example. otherwise if you are definfing it in another page then include the page.

Undefined variable in PHP when referencing MySQL element

Edit: I solved the problem! It was an issue unrelated to the code that I posted - I had an exit command in the script - but all of your advice still helped in other ways.
I'm trying to automatically send an e-mail to a user when they fill out their picks on a sports website. The early part of the script works: Their picks are correctly inserted or updated in the database. The script breaks when I try to pull the user's e-mail address from a table in the MySQL database and use it to send them a message. But what is very strange about this bug is that it doesn't result in any error messages, and for some reason prevents certain echo statements from running while allowing others.
Here's the relevant code:
...
//set variable for the userID, grabbed from the session array
$userID = $_SESSION['identifier'];
...
//write query to get user's e-mail from the database
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
//execute query
$result = $db->query($getEmail);
//check if query failed
try
{
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set e-mail variable
$email = $row['email'];
//set up e-mail information to send a record of their picks to the user
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
//take the info the user submitted, format it for the e-mail, and assign to variable $mailContent
//the $winner1, $spread1, etc. variables are defined earlier in the function, and were successfully submitted into the database
$mailContent = "You picked $winner1 to win by $spread1 points, $winner2 to win by $spread2 points, $winner3 to win by $spread3 points, $winner4 to win by $spread4 points, and $winner5 to win by $spread5 points. \n".
"You can change your picks at any time before 1:00pm EST, February 27, 2011. Just go back to the form on the game page and enter your new picks. Good luck!";
//use wordwrap to limit lines of $mailContent to 70 characters
$mailContent = wordwrap($mailContent, 70);
//send the e-mail
$isMailed = mail($toAddress, $subject, $mailContent, $fromAddress);
//debug: check if mail failed
if (!$isMailed)
{
echo "Mail failed.";
}
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
//if everything succeeded, write reply and close database
echo $reply;
$db->close();
?>
Just to be clear, $userID is set correctly, because their picks enter the database like they're supposed to. None of the exceptions listed in the code come up, meaning the query seems to have run successfully. I checked the query again by copying it from the PHP code and running it directly on the MySQL database. When it ran directly, it found the correct e-mail address for every userID value I entered.
But the mail never gets delivered, and when I try to echo the $email and $toAddress variables to see if they're empty:
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
...nothing shows up. Not even an error message. And that doesn't necessarily mean that the variables are empty: Not even the labels are echoed.
I also tried the code with my personal e-mail hardcoded instead of $toAddress, and no mail was sent. So the mail function isn't working.
I should also note that the script still successfully echoes $reply (which is a string defined much earlier) at the end.
What's really strange is that the login script for my website uses an almost identical piece of code and works perfectly:
$getuserID = "SELECT `userID` FROM `useraccounts` WHERE `u_name` = '".$login."' AND `p_word` = SHA1('".$password."')";
$result = $db->query($getuserID);
//check if query ran, catch exception if it failed
try
{
if ($result === false)
{
throw new customexception("Some kind of database problem occurred when trying to find your user ID.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get info from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set userID variable
$userID = $row['userID'];
//assign the session identifier and include successfullogin.html if all is well
$_SESSION['identifier'] = $userID;
And I used to have the signup script send me an e-mail every time I got a new user, so I know that mail() works in general with my hosting provider:
//set up static e-mail information
$toAddress = "myemail#mysite.com";
$subject = "Advance Sign-Up";
$mailContent = "Name: $firstName $lastName \n".
"Username: $username \n".
"Password: $password \n".
"E-mail: $email \n".
"Country: $country \n".
"State: $state \n".
"City: $city \n".
"ZIP: $zip \n";
$fromAddress = "From: $email";
...
mail($toAddress, $subject, $mailContent, $fromAddress);
This bug is completely mystifying to me. I wish I had some sort of error message to work with, at least. Can anyone see what's wrong?
It should be a comment but for the sake of formatting.
Your way of error handling is quite unusual.
If you really want to use exceptions, it should be done different way: one try block and multiple throws:
try
{
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
$result = $db->query($getEmail);
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
$row = $result->fetch_assoc();
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
$email = $row['email'];
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
$mailContent = "yadda yadda yadda";
$mailContent = wordwrap($mailContent, 70);
mail($toAddress, $subject, $mailContent, $fromAddress);
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
?>
Are you positive the database variables have contents? I use echo (or print) to quickly make sure the variables aren't empty. Are you positive your email code works? Try it with set values (such as your own personal e-mail) to make sure it works.
The best way out to ignore such notices is to ensure that the variables exist or in plain PHP, use isset(),if !isset() throw an exception/error and handle it properly.

Creating a mechanism to validate emails

I already have an advanced user login/register system on my website (colemansystems.psm2.co.uk). However, I would like to have a email sent to new users for verification of their email address. If they have not clicked the link they will not be able to access their account. I am semi-experienced with PHP and MySQL, so please explain in depth.
The code I'm using for the verify.php file (the link the user click on with a GET (for example, verify.php?d=51773199320))
$secret = $_GET['d'];
$result = mysql_query("SELECT valid FROM users WHERE secret=$secret");
while ($row = mysql_fetch_array($result))
{
$valid = $row['valid'];
}
if ($valid == "") {
echo"There seems to be a problem with the verification code.<br><br><br><br><br>";
}
elseif ($valid == "1")
{
echo"Your account is already verified.<br><br><br><br><br>";
}
else
{
mysql_query("UPDATE users SET valid = '1' WHERE secret=$secret");
echo "Thank you, your account is now verified and you are free to use the exclusive features!<br><br><br><br><br><br>";
}
Is this secure?
The easiest way is not to register unverified users at all.
Ask them for an email address and send email with a link that contains this address sealed with a hash. Upon receiving this link you can start the registration process.
Something like this
$secret = "35onoi2=-7#%g03kl";
$email = urlencode($_POST['email']);
$hash = MD5($_POST['email'].$secret);
$link = "http://example.com/register.php?email=$email&hash=$hash";
And in your register.php add 2 hidden fields to the registration form - email and hash, storing their received values from GET.
Finally, process registration and check,
if (md5($_POST['email'].$secret) == $_POST['hash']) {
//Continue registration.
}
Easiest for whom - user, coder, computer?
What are you optimizing - the quantity of keypresses, the size of the code, the user experience?
The easiest to code is probably unsafe.
You should check the email address for correctness before sending a letter to it.
after registration create a hashed string and save it to the temporary user table send that hashed string to the user email address using this code
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";
}
and after that create a verify page and then
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'");
}
}
if you have any problem here is a complete tutorial http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php

Categories