0
<?php
// configure
$from = 'Demo contact form <demo@domain.com>';
$sendTo = '105 Questions <myemail@example.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' =>       'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable    name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please  try again later';
// let's do the sending

try
{
$emailText = "You have new message from the website\n=============================\n";

foreach ($_POST as $key => $value) {

    if (isset($fields[$key])) {
        $emailText .= "$fields[$key]: $value\n";
    }
}

mail($sendTo, $subject, $emailText, "From: " . $from);

$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' =>   $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);

header('Content-Type: application/json');

echo $encoded;
}
else {
echo $responseArray['message'];
} 

This is where I get a little confused some code end with just } and I got errors.

But when I add ?> it works, but also sends an email on page load.

In another post I read they fixed it with isset but when I put it before the "configure comment" an email was still sent on page load.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
etnuh
  • 17
  • 5
  • php runs on page load. you have no logic in the code that would stop `mail()` from being executed – Memor-X Sep 28 '16 at 03:49
  • Do i add "exit" at the beginning of my code to stop the php from running? – etnuh Sep 28 '16 at 03:57
  • check for a submit and run it under – Sanooj T Sep 28 '16 at 04:04
  • @etnuh well....yes but then what's the point to any of the code then? putting [`exit` or `die`](http://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php) at the start of your code prevents any of it, or the rest of the page for that matter, from loading thus making it a complete waste. if you really need to to use them at the start of your code use some logic to indicate when the page should't load – Memor-X Sep 28 '16 at 04:08
  • @Memor-X Ok thanks for your input i will try to fix this – etnuh Sep 28 '16 at 04:16

1 Answers1

0

Basic logic - don't send the message unless you're handling a form submission rather than a page load.

if (isset($_POST['name'])) { //This will not be true on a page load
    //Your existing script goes here
}
Synchro
  • 35,538
  • 15
  • 81
  • 104