Da. Syntex Da. Syntex - 2 months ago 7
HTML Question

PHP Mail not working when redirecting

I am creating a contact form for my website and I am having slight problems. It works fine when not using location and I get an email but when using location I do not get an email when entering the form.

How can I redirect and get the email at the same time?

HTML:



<div class="contact-form">
<div class="contact-form-container">
<form novalidate action="index.php" method="POST">
<label id="label-0">Position</label>
<select name="position_form">
<option value="collaboration_partner">Samarbetspartner</option>
<option value="youth_organization">Ungdomsorginisation</option>
<option value="young_enterprise">Ung Företagsamhet</option>
<option value="work_group">Arbetsgrupp</option>
<option value="school">Skola</option>
<option value="volunteer_trainee">Volontär/Praktikant</option>
<option value="charity">Välgörenhet</option>
<option value="sponsor">Sponsor</option>
<option value="other">Annat</option>
</select>

<label id="label-1">Namn</label>
<input name="name" placeholder="Namn" type="text">

<label id="label-2">Email Adress</label>
<input name="email" type="text" placeholder="Email Adress">

<label id="label-3">Meddelande</label>
<textarea name="message" placeholder="Meddelande"></textarea>

<input id="submit" name="submit" type="submit" value="SKICKA">
</form>
</div>
</div>





PHP:



<?php

$to = "random@protonmail.com";
$subject = "Kontakta Oss - Senaste Meddelande";
$name = $_POST['name'];
$email = $_POST["email"];
$position_form = $_POST["position_form"];
$message = $_POST["message"];



$body = <<<EMAIL

Namn:
$name

Email:
$email

Position:
$position_form

Meddelande:
$message

EMAIL;

$header = "from: kontakt@example.com";
header('Location: http://example.com/redirecthere.php');
exit();

if($_POST){
mail($to, $subject, $body, $header);
}
?>




Answer

The mail function is called (in fact, it's never called) after the header('Location. Even if you remove the header it wouldn't send mail because there's an exit function called before you get the if.

Remove the exit and move the header to the end of the file

Comments