Jump to content

PHP Error Warning: mail(): Failed to connect to mailserver


Recommended Posts

Could anyone please help me with the problem I am currently having, when users try to register it allows them to register, however when I try to register users they don't get an confirmation email sent to their email as I am getting a error which says that mail(); failed to connect to mail-server., please help or advise.

 

The error I am currently getting says that it failed to connect to mailserver, please advise or help.

 

Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\bradvisor_login_api\index.php on line <i>163</i></th></tr>
    Index.PHP File:
 
<?php

/**
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 **/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];

    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
            
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } 
  else if ($tag == 'chgpass'){
  $email = $_POST['email'];

  $newpassword = $_POST['newpas'];
  

  $hash = $db->hashSSHA($newpassword);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  $subject = "Change Password Notification";
         $message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nLearn2Crack Team.";
          $from = "contact@learn2crack.com";
          $headers = "From:" . $from;
	if ($db->isUserExisted($email)) {

 $user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($email,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}
}
else if ($tag == 'forpass'){
$forgotpassword = $_POST['forgotpassword'];

$randomcode = $db->random_string();
  

$hash = $db->hashSSHA($randomcode);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  $subject = "Password Recovery";
         $message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nLearn2Crack Team.";
          $from = "contact@learn2crack.com";
          $headers = "From:" . $from;
	if ($db->isUserExisted($forgotpassword)) {

 $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($forgotpassword,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}

}
else if ($tag == 'register') {
        // Request type is Register new user
        $fname = $_POST['fname'];
		$lname = $_POST['lname'];
        $email = $_POST['email'];
		$uname = $_POST['uname'];
        $password = $_POST['password'];


        
          $subject = "Registration";
         $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";
          $from = "contact@learn2crack.com";
          $headers = "From:" . $from;

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
           else if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Invalid Email Id";
            echo json_encode($response);             
}
else {
            // store user
            $user = $db->storeUser($fname, $lname, $email, $uname, $password);
            if ($user) {
                // user stored successfully
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
               mail($email,$subject,$message,$headers);
            
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "JSON Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
         $response["error"] = 3;
         $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
} else {
    echo "BradVisor Login API";
}
?>

PHP.INI File

 

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25


; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = you@yourdomain

 

 

Edited by james_martin_187
Link to comment
Share on other sites

With those mail settings, emails will only work if you have an SMTP server installed locally. PHP does not come with a mailer server.

 

I recommend you use something like PHPMailer or SwitfMailer and configure them to use an existing SMTP service (such as gmail) for sending emails.

Link to comment
Share on other sites

I am having probemms with connfiguring PHPMailer into my project folder. I have downloalded the full phpmailer file into my www folder, called it phpmailer and then I have also created a mailer.php file inside my www folder in wamp server which has allowed me to send out mail, however it does not send out mail from my project folder as it says.

 

Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\bradvisor_login_api\index.php on line <i>163</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>

phppmailer.php File

v<?php

require 'PHPMailer/PHPMailerAutoload.php';
 
$mail = new PHPMailer;
 
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'bradvisor15@gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
 
$mail->From = 'bradvisor15@gmail.com';
$mail->FromName = 'BradVisor';
$mail->addAddress('safyannawaz@hotmail.com', 'Anil Nawaz');
 
$mail->addReplyTo('haleema73@hotmail.co.uk', 'Anil Nawaz');
 
$mail->WordWrap = 50;
$mail->isHTML(true);
 
$mail->Subject = 'PHPMailer';
$mail->Body    = 'Hi, Test email';
 
if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}
 
echo 'Message has been sent';

?>

The above works, however I need it to work in my project which does not work at the moment, could you please help or advice.

Edited by james_martin_187
Link to comment
Share on other sites

You would use that code, to replace where you using php's mail() function

 

To have the email sent to the email address the user entered in your registration form, you would pass the variables that contains the users email address and name to the $mail->addAddress() function in your registration code.

Link to comment
Share on other sites

Ch0cu3r Could you please advise as I have never done this type of thing before as lamp server comes with mail fucction, however wamp server does not. I have pasted my index.php code below which should send users email once they register, change password or if they have forgotten their password. please could you advise and help.

<?php

/**
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 **/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];

    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
            
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } 
  else if ($tag == 'chgpass'){
  $email = $_POST['email'];

  $newpassword = $_POST['newpas'];
  

  $hash = $db->hashSSHA($newpassword);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  $subject = "Change Password Notification";
         $message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nLearn2Crack Team.";
          $from = "contact@learn2crack.com";
          $headers = "From:" . $from;
	if ($db->isUserExisted($email)) {

 $user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($email,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}
}
else if ($tag == 'forpass'){
$forgotpassword = $_POST['forgotpassword'];

$randomcode = $db->random_string();
  

$hash = $db->hashSSHA($randomcode);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  $subject = "Password Recovery";
         $message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nLearn2Crack Team.";
          $from = "contact@bradvisor.com";
          $headers = "From:" . $from;
	if ($db->isUserExisted($forgotpassword)) {

 $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($forgotpassword,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}

}
else if ($tag == 'register') {
        // Request type is Register new user
        $fname = $_POST['fname'];
		$lname = $_POST['lname'];
        $email = $_POST['email'];
		$uname = $_POST['uname'];
        $password = $_POST['password'];


        
          $subject = "Registration";
         $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";
          $from = "contact@bradvisor.com";
          $headers = "From:" . $from;

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
           else if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Invalid Email Id";
            echo json_encode($response);             
}
else {
            // store user
            $user = $db->storeUser($fname, $lname, $email, $uname, $password);
            if ($user) {
                // user stored successfully
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
               mail($email,$subject,$message,$headers);
            
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "JSON Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
         $response["error"] = 3;
         $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
} else {
    echo "BradVisor Login API";
}
?>
Link to comment
Share on other sites

For example I would replace your following code

$subject = "Change Password Notification";
$message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nLearn2Crack Team.";
$from = "contact@learn2crack.com";
$headers = "From:" . $from;
mail($email,$subject,$message,$headers);

With the following

require_once 'phpmailer.php';

// sets the email subjuct
$mail->Subject = "Change Password Notification";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nLearn2Crack Team.";

// who the email was sent from (your email)
$mail->From = "contact@learn2crack.com";

// the email address you are sending this email to
$mail->addAddress($email);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}

NOTE: In phpmailer.php you would only want to keep the first 12 lines of code, the rest of the lines will need to be deleted. If you still want the wordwrap and html email format then keep these two lines

$mail->WordWrap = 50;
$mail->isHTML(true);

Have a go at converting the two other instances where you use mail().

Link to comment
Share on other sites

Ch0cu3r could you please advise, I have done what you have told me however now i am getting an error on line 216, please help?.

 

Index.PHP File

<?php

/**
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 **/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];

    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
            
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } 
  else if ($tag == 'chgpass'){
  $email = $_POST['email'];

  $newpassword = $_POST['newpas'];
  

  $hash = $db->hashSSHA($newpassword);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Change Password Notification";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nBradVisor Team.";

// who the email was sent from (your email)
$mail->From = "contact@BradVisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}
	if ($db->isUserExisted($email)) {

 $user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($email,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}
}
else if ($tag == 'forpass'){
$forgotpassword = $_POST['forgotpassword'];

$randomcode = $db->random_string();
  

$hash = $db->hashSSHA($randomcode);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
   require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Password Recovery";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";

// who the email was sent from (your email)
$mail->From = "contact@bradvisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}
	if ($db->isUserExisted($forgotpassword)) {

 $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          mail($forgotpassword,$subject,$message,$headers);
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}

}
else if ($tag == 'register') {
        // Request type is Register new user
        $fname = $_POST['fname'];
		$lname = $_POST['lname'];
        $email = $_POST['email'];
		$uname = $_POST['uname'];
        $password = $_POST['password'];


        require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Registration";

// sets the body of the email
$mail->Body = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";

// who the email was sent from (your email)
$mail->From = "contact@bradvisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
           else if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Invalid Email Id";
            echo json_encode($response);             
}
else {
            // store user
            $user = $db->storeUser($fname, $lname, $email, $uname, $password);
            if ($user) {
                // user stored successfully
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
               mail($email,$subject,$message,$headers);
            
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "JSON Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
         $response["error"] = 3;
         $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
} else {
    echo "BradVisor Login API";
}
?>

Error message which I get.

 

<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: message in C:\wamp\www\bradvisor_login_api\index.php on line <i>216</i></th></tr>


    
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: headers in C:\wamp\www\bradvisor_login_api\index.php on line <i>216</i></th></tr>
   
Link to comment
Share on other sites

Ok, didn't look at your code properly you posted earlier. Remember you need to be replacing where you use mail() with the phpmailer code, as I suggested in my earlier reply here. You have placed the phpmailer code incorrectly. This is why you are getting email twice.

 

 

I now get a java nullpoint error,

Java? PHP has nothing do with that.

Link to comment
Share on other sites

Forgotten password and reset password does now work, however when registerng a new user the application just closes and says an unexpectable errror occrred, giving no errors. Could you please advice. The user does get enterned into the database and they get an email sent, however the application just cloes.

 

Index.PHP File

<?php

/**
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 **/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // Get tag
    $tag = $_POST['tag'];

    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
            
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } 
  else if ($tag == 'chgpass'){
  $email = $_POST['email'];

  $newpassword = $_POST['newpas'];
  

  $hash = $db->hashSSHA($newpassword);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
  require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Change Password Notification";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nBradVisor Team.";

// who the email was sent from (your email)
$mail->From = "contact@BradVisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}
	if ($db->isUserExisted($email)) {

 $user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
          
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}
}
else if ($tag == 'forpass'){
$forgotpassword = $_POST['forgotpassword'];

$randomcode = $db->random_string();
  

$hash = $db->hashSSHA($randomcode);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"];
   require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Password Recovery";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";

// who the email was sent from (your email)
$mail->From = "contact@bradvisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}
	if ($db->isUserExisted($forgotpassword)) {

 $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
         $response["success"] = 1;
           require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Password Recovery";

// sets the body of the email
$mail->Body = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";

// who the email was sent from (your email)
$mail->From = "contact@bradvisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}
         echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


            // user is already existed - error response
           
           
        } 
           else {

            $response["error"] = 2;
            $response["error_msg"] = "User not exist";
             echo json_encode($response);

}

}
else if ($tag == 'register') {
        // Request type is Register new user
        $fname = $_POST['fname'];
		$lname = $_POST['lname'];
        $email = $_POST['email'];
		$uname = $_POST['uname'];
        $password = $_POST['password'];


        require_once 'mailer.php';

// sets the email subjuct
$mail->Subject = "Registration";

// sets the body of the email
$mail->Body = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";

// who the email was sent from (your email)
$mail->From = "contact@bradvisor.com";

// the email address you are sending this email to
$mail->addAddress($email);

$mail->WordWrap = 50;
$mail->isHTML(true);

// make sure email did not return error message
if(!$mail->send())
{
    trigger_error('Unable to send mail! Mail error: ' . $mail->ErrorInfo);
}

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
           else if(!$db->validEmail($email)){
            $response["error"] = 3;
            $response["error_msg"] = "Invalid Email Id";
            echo json_encode($response);             
}
else {
            // store user
            $user = $db->storeUser($fname, $lname, $email, $uname, $password);
            if ($user) {
                // user stored successfully
            $response["success"] = 1;
            $response["user"]["fname"] = $user["firstname"];
            $response["user"]["lname"] = $user["lastname"];
            $response["user"]["email"] = $user["email"];
	    $response["user"]["uname"] = $user["username"];
            $response["user"]["uid"] = $user["unique_id"];
            $response["user"]["created_at"] = $user["created_at"];
     
            
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "JSON Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
         $response["error"] = 3;
         $response["error_msg"] = "JSON ERROR";
        echo json_encode($response);
    }
} else {
    echo "BradVisor Login API";
}
?>

Userfunction.PHP File

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
		$db = new DB_Connect();
        $this->db = $db->connect();
        
    }

    // destructor
    function __destruct() {
        
    }


    /**
     * Random string which is sent by mail to reset password
     */

public function random_string()
{
    $character_set_array = array();
    $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
    $character_set_array[] = array('count' => 1, 'characters' => '0123456789');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return implode('', $temp_array);
}


public function forgotPassword($forgotpassword, $newpassword, $salt){
	$result = mysqli_query($this->db, "UPDATE `users` SET `encrypted_password` = '$newpassword',`salt` = '$salt' 
						  WHERE `email` = '$forgotpassword'");

if ($result) {
 
return true;

}
else
{
return false;
}

}
/**
     * Adding new user to mysqli database
     * returns user details
     */

    public function storeUser($fname, $lname, $email, $uname, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysqli_query($this->db,"INSERT INTO `users`(`unique_id`, `firstname`, `lastname`, `username`, `email`, `encrypted_password`, `salt`, `created_at`) VALUES('$uuid', '$fname', '$lname', '$uname', '$email', '$encrypted_password', '$salt', NOW())") or die(mysqli_error($db)); 
		                                  
  // check for successful store
        if ($result) {
            // get user details 
            $uid = mysqli_insert_id($this->db); // last inserted id
            $result = mysqli_query($this->db, "SELECT * FROM users WHERE uid = $uid") or die(mysqli_error($this->db));
            // return user details
            return mysqli_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Verifies user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysqli_query($this->db, "SELECT * FROM users WHERE email = '$email'") or die(mysqli_error($this->db));
        // check for result 
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysqli_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }
	
	/**
     * Checks whether the email is valid or fake
     */
public function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || 
 ↪checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

/**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysqli_query($this->db, "SELECT email from users WHERE email = '$email'") or die(mysqli_error($this->db));
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

    /**
     * Encrypting password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>
Link to comment
Share on other sites

Forgotten password is not working as well as it is giving errors on line 123 and 150. please could you advise?. it send the user an email however the application just crashes. 

 

Notice: Undefined variable: email in C:\wamp\www\bradvisor_login_api\index.php on line <i>123</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>


Notice: Undefined variable: email in C:\wamp\www\bradvisor_login_api\index.php on line <i>150</i></th></tr>
Link to comment
Share on other sites

Gone through and cleaned up your code a bit, and made a resuable function for calling the phpmailer code

<?php
 
/*
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 */

require_once 'phpmailer.php';
 
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
 
    // check for tag type
    switch($_POST['tag'])
    {
        case 'login':
            // Request type is check Login
            $email = $_POST['email'];
            $password = $_POST['password'];
     
            // check for user
            $user = $db->getUserByEmailAndPassword($email, $password);
            if ($user != false)
            {
                // user found
                // echo json with success = 1
                $response["success"] = 1;
                $response["user"]["fname"] = $user["firstname"];
                $response["user"]["lname"] = $user["lastname"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["uname"] = $user["username"];
                $response["user"]["uid"] = $user["unique_id"];
                $response["user"]["created_at"] = $user["created_at"];
            }
            else
            {
                // user not found
                // echo json with error = 1
                $response["error"] = 1;
                $response["error_msg"] = "Incorrect email or password!";
            }
        break;

        case 'chgpass':
            $email = $_POST['email'];
            $newpassword = $_POST['newpas'];

            $hash = $db->hashSSHA($newpassword);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Change Password Notification";
                    $message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nLearn2Crack Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            }
        break;

        case 'forpass':
            $email = $_POST['forgotpassword'];
            $randomcode = $db->random_string();
      
            $hash = $db->hashSSHA($randomcode);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Password Recovery";
                    $message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nLearn2Crack Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            } 
        break;

        case 'register':
            // Request type is Register new user
            $fname = $_POST['fname'];
            $lname = $_POST['lname'];
            $email = $_POST['email'];
            $uname = $_POST['uname'];
            $password = $_POST['password'];
     
            // check if user is already existed
            if ($db->isUserExisted($email))
            {
                // user is already existed - error response
                $response["error"] = 2;
                $response["error_msg"] = "User already existed";
            } 
            else if(!$db->validEmail($email))
            {
                $response["error"] = 3;
                $response["error_msg"] = "Invalid Email Id";          
            }
            else
            {
                // store user
                $user = $db->storeUser($fname, $lname, $email, $uname, $password);
                if ($user)
                {
                    // user stored successfully
                    $response["success"] = 1;
                    $response["user"]["fname"] = $user["firstname"];
                    $response["user"]["lname"] = $user["lastname"];
                    $response["user"]["email"] = $user["email"];
                    $response["user"]["uname"] = $user["username"];
                    $response["user"]["uid"] = $user["unique_id"];
                    $response["user"]["created_at"] = $user["created_at"];

                    $subject = "Registration";
                    $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";

                    $name = $user['firstname'] . ' ' . $user['lastname'];
                    send_mail($subject, $message, $email, $name);
                }
                else
                {
                    // user failed to store
                    $response["error"] = 1;
                    $response["error_msg"] = "JSON Error occured in Registartion";
                }
            }
        break;

        default:
            $response["error"] = 3;
            $response["error_msg"] = "JSON ERROR";
    }

    echo json_encode($response);
}
else
{
    echo "BradVisor Login API";
}

Code for phpmailer.php

<?php
 
require_once 'PHPMailer/PHPMailerAutoload.php';

function send_email($subject, $message, $to, $name = null)
{
    $mail = new PHPMailer;
 
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'bradvisor15@gmail.com';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'tls';

    $mail->From = "contact@learn2crack.com";;
    $mail->FromName = 'Learn2crack';

    $mail->WordWrap = 50;
    $mail->isHTML(true);

    $mail->addAddress($to, $name);
    $mail->Subject = $subject;
    $mail->Body    = $message;
 
    if(!$mail->send())
    {
       trigger_error('Unable to send email. Error: ' . $mail->errorInfo);
    }
}
Link to comment
Share on other sites

Ch0cu3r I am now getting two errors when I try to register a user could you please help.

 

Errors which i getting are below:

 Notice: Undefined variable: tag in C:\wamp\www\bradvisor_login_api\index.php on line <i>16</i></th></tr>    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>


 Fatal error: Call to undefined function send_mail() in C:\wamp\www\bradvisor_login_api\index.php on line <i>152</i></th></tr>
Line 152
 
send_mail($subject, $message, $email, $name);

Index.PHP File

<?php
 
/*
 PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
 */

require_once 'mailer.php';
 
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
    // Include Database handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();
    
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
 
    // check for tag type
    switch($_POST['tag'])
    {
        case 'login':
            // Request type is check Login
            $email = $_POST['email'];
            $password = $_POST['password'];
     
            // check for user
            $user = $db->getUserByEmailAndPassword($email, $password);
            if ($user != false)
            {
                // user found
                // echo json with success = 1
                $response["success"] = 1;
                $response["user"]["fname"] = $user["firstname"];
                $response["user"]["lname"] = $user["lastname"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["uname"] = $user["username"];
                $response["user"]["uid"] = $user["unique_id"];
                $response["user"]["created_at"] = $user["created_at"];
            }
            else
            {
                // user not found
                // echo json with error = 1
                $response["error"] = 1;
                $response["error_msg"] = "Incorrect email or password!";
            }
        break;

        case 'chgpass':
            $email = $_POST['email'];
            $newpassword = $_POST['newpas'];

            $hash = $db->hashSSHA($newpassword);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Change Password Notification";
                    $message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nBradVisor Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            }
        break;

        case 'forpass':
            $email = $_POST['forgotpassword'];
            $randomcode = $db->random_string();
      
            $hash = $db->hashSSHA($randomcode);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];

            if ($db->isUserExisted($email))
            {
                $user = $db->forgotPassword($email, $encrypted_password, $salt);
                if ($user)
                {
                    $response["success"] = 1;

                    $subject = "Password Recovery";
                    $message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";
                    send_email($subject, $message, $email);
                }
                else
                {
                    $response["error"] = 1;
                }
                // user is already existed - error response
            } 
            else
            {
                $response["error"] = 2;
                $response["error_msg"] = "User not exist";
            } 
        break;

        case 'register':
            // Request type is Register new user
            $fname = $_POST['fname'];
            $lname = $_POST['lname'];
            $email = $_POST['email'];
            $uname = $_POST['uname'];
            $password = $_POST['password'];
     
            // check if user is already existed
            if ($db->isUserExisted($email))
            {
                // user is already existed - error response
                $response["error"] = 2;
                $response["error_msg"] = "User already existed";
            } 
            else if(!$db->validEmail($email))
            {
                $response["error"] = 3;
                $response["error_msg"] = "Invalid Email Id";          
            }
            else
            {
                // store user
                $user = $db->storeUser($fname, $lname, $email, $uname, $password);
                if ($user)
                {
                    // user stored successfully
                    $response["success"] = 1;
                    $response["user"]["fname"] = $user["firstname"];
                    $response["user"]["lname"] = $user["lastname"];
                    $response["user"]["email"] = $user["email"];
                    $response["user"]["uname"] = $user["username"];
                    $response["user"]["uid"] = $user["unique_id"];
                    $response["user"]["created_at"] = $user["created_at"];

                    $subject = "Registration";
                    $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";

                    $name = $user['firstname'] . ' ' . $user['lastname'];
                    send_mail($subject, $message, $email, $name);
                }
                else
                {
                    // user failed to store
                    $response["error"] = 1;
                    $response["error_msg"] = "JSON Error occured in Registartion";
                }
            }
        break;

        default:
            $response["error"] = 3;
            $response["error_msg"] = "JSON ERROR";
    }

    echo json_encode($response);
}
else
{
    echo "BradVisor Login API";
}

mailer.php File

<?php
 
require_once 'PHPMailer/PHPMailerAutoload.php';

function send_email($subject, $message, $to, $name = null)
{
    $mail = new PHPMailer;
 
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'bradvisor15@gmail.com';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'tls';

    $mail->From = "contact@BradVisor.com";;
    $mail->FromName = 'BradVisor';

    $mail->WordWrap = 50;
    $mail->isHTML(true);

    $mail->addAddress($to, $name);
    $mail->Subject = $subject;
    $mail->Body    = $message;
 
    if(!$mail->send())
    {
       trigger_error('Unable to send email. Error: ' . $mail->errorInfo);
    }
}
Edited by james_martin_187
Link to comment
Share on other sites

Change the smpt settings, here

$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'bradvisor15@gmail.com';
$mail->Password = 'password'; 

to use the account for contact@bradvisor.com

 

I dont have an account called this, I only have a gmail account called bradvisor15@gmail.com

Edited by james_martin_187
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.