Link to home
Start Free TrialLog in
Avatar of Ivan Golubar
Ivan Golubar

asked on

Adding PHPMailer to an existing *.php

I have  3   <?php  ?>.  They are part of signup.php. In third one i did comment mail() ; function.

Because I want to use  an extra <?php  ?>, where i want to implement PHPMailer to send emails.  That one will then use $e variable (address where to send the email) from
 the third  <?php  ?>

But it is not functioning all together. Can you pleas  help me make  it work?
For info: If  I put next  part
$mail = new PHPMailer(true);                              
try {
............
}

Open in new window

from the fourth  <?php  ?> into comments, then the page loads.
And another info:  I can use  PHPMailer library as separate app. So, my PHPMailer settings are Ok.

<?php  
...
...
?>
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
	include_once("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
	$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
	$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
    $uname_check = mysqli_num_rows($query);
    if (strlen($username) < 3 || strlen($username) > 16) {
	    echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
	    exit();
    }
	if (is_numeric($username[0])) {
	    echo '<strong style="color:#F00;">Usernames must begin with a letter aha</strong>';
	    exit();
    }
    if ($uname_check < 1) {
	    echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
	    exit();
    } else {
	    echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
	    exit();
    }
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
	// CONNECT TO THE DATABASE
	include_once("../php_includes/db_conx.php");
	// GATHER THE POSTED DATA INTO LOCAL VARIABLES
	$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
	$e = mysqli_real_escape_string($db_conx, $_POST['e']);
	$p = $_POST['p'];
	$g = preg_replace('#[^a-z]#', '', $_POST['g']);
	$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
	// GET USER IP ADDRESS
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
	// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
	$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
	$u_check = mysqli_num_rows($query);
	// -------------------------------------------
	$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
	$e_check = mysqli_num_rows($query);
	// FORM DATA ERROR HANDLING
	if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
		echo "The form submission is missing values ma kaj.";
        exit();
	} else if ($u_check > 0){ 
        echo "The username you entered is alreay taken";
        exit();
	} else if ($e_check > 0){ 
        echo "That email address is already in use in the system";
        exit();
	} else if (strlen($u) < 3 || strlen($u) > 16) {
        echo "Username must be between 3 and 16 characters";
        exit(); 
    } else if (is_numeric($u[0])) {
        echo 'Username cannot begin with a number';
        exit();
    } else {
	// END FORM DATA ERROR HANDLING
	    // Begin Insertion of data into the database
		// Hash the password and apply your own mysterious unique salt
		
		
		$p_hash = md5($p);
		// Add user info into the database table for the main site table
		$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)       
		        VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
		$query = mysqli_query($db_conx, $sql); 
		$uid = mysqli_insert_id($db_conx);
		// Establish their row in the useroptions table
		$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
		$query = mysqli_query($db_conx, $sql);
		// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
		    if (!file_exists("../user/$u")) {
			mkdir("../user/$u", 0755);
		}
		  if (!file_exists("../user/$u/projectsList2")) {
			mkdir("../user/$u/projectsList2", 0755);
		}
		// Email the user their activation link
	/*$to = "$e";							 
		$from = "xxxxxxxxxxx";
		$subject = 'xxxxxxxxxxxxxxx';
		$message = 'xxxxxxxxxxx';
		$headers = "From: $from\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\n";
		mail($to, $subject, $message, $headers);
		echo "signup_success";*/
		exit();
	}
	exit();
}
?>	
<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require  '../vendor/autoload.php';

$mail = new PHPMailer(true);                              
try {
    //Server settings
    $mail->SMTPDebug = 2;                                
    $mail->isSMTP();                                      
    $mail->Host = 'xxxxxxxxxxxxx';                     
    $mail->SMTPAuth = true;                               
    $mail->Username = 'xxxxxxxxxx';              
    $mail->Password = 'xxxxxxxxxxxxxx';                          
    $mail->SMTPSecure = 'tls';                            
    $mail->Port = 587;                                    

    //Recipients
    $mail->setFrom('xxxxxxxxxxxxxx');
    $mail->addAddress('xxxxxxxxxxx);     
   // $mail->addAddress('xxxxxxxxxx');               

   // $mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');
  //
  
    //Content
    $mail->isHTML(true);                                  
    $mail->Subject = 'xxxxxxxxxxxxxx';
    $mail->Body    = '';
	
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    
} 
?>

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You need to tell us what is not working.

You say when you call your script with just PHPMailer it is working so your settings are good.

The other 3 scripts - we would need to see those AND we would need to now how they are not working
a) are there errors
b) does the script just not send the email

You have verbose set on
$mail->SMTPDebug = 2;  

Open in new window

What output does that produce?
Avatar of Ivan Golubar
Ivan Golubar

ASKER

You need to tell us what is not working.
Page is not loading. Next is what shows the browser:
This page isn’t working
myPage.com is currently unable to handle this request.
HTTP ERROR 500


You have verbose set on What output does that produce?
Can not tell because page is not loading.

There is all code in my previous post.
PHP part of signup.php file is  made as next;

<?php 1  ?>      //something
<?php 2  ?>      // something
<?php 3  ?>      // here you may see that I commented email(); function
<?php 4  ?>      //sending of email

I could send email when I used only <?php 4  ?>  as code in testEmailSending.php file.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was checking wrong error_log file before. I could see now that I had  next error [26-Jul-2018 23:14:59 UTC] PHP Fatal error:  Cannot use try without catch or finally in /............/signup.php on line 116

I did resolve it with  adding of:
catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

Open in new window


to line 140  of previous post attached code.