Search code examples
phpmysqlphpmailerserver-side

How to get PHP variable from another file?


I'm trying to make a forgot password system with PHPMailer on xampp. But when I send an email,the email body is a html mail template,what I get from another file $mail->Body = file_get_contents('mail_template.php');,and I have problem,because I don't know how should I get the data of the $url variable and send it to mail_template.php file to use it for the link in the mail. I tried the include 'filename.php'; command,but haven't worked.

Here is the code:

if (isset($_POST["submitButton"])) {
    $emailTo = $_POST["email"];

    $code = md5(uniqid(rand(), true));
    $query = $con->prepare("INSERT INTO resetpasswords(code,email) VALUES('$code', '$emailTo')");
    $query->execute();
    if (!$query) {
        exit("Something went wrong...");
    }

    $mail = new PHPMailer(true);

    try {
        //Server settings                                           // Enable verbose debug output
        $mail->isSMTP();                                            // Send using SMTP
        $mail->Host = 'smtp.gmail.com';                    // Set the SMTP server to send through
        $mail->SMTPAuth = true;                                   // Enable SMTP authentication
        $mail->Username = 'mail@gmail.com';                     // SMTP username
        $mail->Password = 'password';                               // SMTP password
        $mail->SMTPSecure = 'ssl';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

        //Recipients
        $mail->setFrom('mail@mail.com', 'Email');
        $mail->addAddress($emailTo);     // Add a recipient
        $mail->addReplyTo('no-reply@website.com', 'No reply');


        // Content
        $url = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword/code/$code";
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = 'Reset your password!';
        $mail->Body = file_get_contents('mail_template.php');
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
    } catch (Exception $e) {
        echo "Message could not be sent. Error: {$mail->ErrorInfo}";
    }
    header("refresh:10;url=login.php");
}

So from this php file,I want to send the data of the $url to the mail_template.php

Is this possible to do?


Solution

  • To send data to another url in php you have to try the following url:

    `mail_template.php?data=mail@gmail.com` 
    

    then inside an empty mail_template.php do -

     <?php 
        if (isset($_GET['data'])) {
          $test = $_GET['data'];
    //print the data added to the url
          echo $test;
        }
        ?>