-1

I have a php page that does a job after a form is submitted. the form enters data into a database then the next page queries the database and creats and sends an email based on the info entered into the form. I need that page to redirect back to the original form after sending the email.

        <?php
    $con = mysqli_connect('localhost','username','password');

if(!$con)
{
    echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'dbname'))
{
    echo 'Database Not Selected';
}

$Name = $_POST['Name'];
$Email = $_POST['Email'];

$sql = "INSERT INTO tablename (Name,Email) VALUES ('$Name','$Email')";

if(!mysqli_query($con,$sql))
{
    echo 'Not Inserted';
}
else
{
    echo 'Blah Blah Blah Yackity Schmackity';
    $id = $con->insert_id; // Get latest inserted id.

    $to      = $Email;
    $subject = 'Subject Line Here';
    $message = '<center><img src="http://domainname.com/images/Banner.jpg" /> 
</center><br><br>start of email text here<b> "'.$Name.'"</b> Your Member ID 
is "'.$id.'"Rest of email text here.
';
    $headers = 'From: email@domainname.com' . "\r\n" .
        'Reply-To: email@domainname.com' . "\r\n" .
        'Content-Type: text/html' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
}   ?>
PCMedicJAX
  • 79
  • 8
  • 3
    Have you tried anything so far with regards to setting up redirection? You're also vulnerable to SQL injection. You should use [**prepared statements**](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) to prevent this. Also ensure that your database user only has the [**required privileges**](https://en.wikipedia.org/wiki/Principle_of_least_privilege). You can refer to [**this post**](http://stackoverflow.com/questions/60174) for further information on how to prevent SQL injection in PHP :) – Obsidian Age Mar 27 '18 at 03:02
  • 2
    `header('Location: '.$url); exit();` All that output first, is gonna kick you, you cant output anything if you do a header redirection. and that stuff ^ – ArtisticPhoenix Mar 27 '18 at 03:05

1 Answers1

0

As the previous comment stated no echoing. Save the success/error message in a session then out put that data to the file being directed to. As the manual states The mail function: Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

if(mail($to, $subject, $message, $headers)){
   $_SESSION['msg'] = 'Your mail was sent';
} else {
  $_SESSION['msg'] = 'Your mail was not sent';
}
header('Location: '.$url); exit();

// Response page
echo htmlspecialchars($_SESSION['msg']);
unset($_SESSION['msg']);
Dre
  • 36
  • 3