I recently made a form for my webpage, but i keep getting emails from my form. Even though i don't send the form i keep getting emails.
And if i do submit my form i get 2 or 3 emails. 1 with the information of my form, and 2 with no information.
php code:
<?php
//reciever
$to = 'julius.kroon@gmail.com';
//subject
$subject = 'new costumer';
//form information
$title = "";
$name = "";
$companyname = "";
$mail = "";
$extrapages = "";
$sow = "";
if(isset($_POST['title'])){ $title = $_POST['title']; } //title
if(isset($_POST['name'])){ $name = $_POST['name']; } //name
if(isset($_POST['companyname'])){ $companyname = $_POST['companyname']; } //company name
if(isset($_POST['mail'])){ $mail = $_POST['mail']; } //email
if(isset($_POST['extrapages'])){ $extrapages = $_POST['extrapages']; } //extra pages
if(isset($_POST['sow'])){ $sow = $_POST['sow']; } //site on web
$message ="
title = $title
name = $name
companyname = $companyname
mail = $mail
extra pages = $extrapages
site on web = $sow
";
//header
$headers = 'From: webmaster@example.com' . "
" .
'X-Mailer: PHP/' . phpversion();
//mail code
mail($to, $subject, $message, $headers);
?>
html code:
<form action="" method="POST">
<em>Last name:</em></br>
<select name="title" id="title">
<option>Mr.</option>
<option>Mrs.</option>
<option>Dr.</option>
</select>
<input type="text" size="25" name="name" id="name" placeholder="Last name" required="required"><p /><br>
<em>company name:</em></br>
<input type="text" size="25" name="companyname" id="companyname" placeholder="Company Name" required="required"><p /><br>
<em>Email:</em></br>
<input type="text" size="25" name="mail" id="mail" placeholder="email" required="required"><p /><br>
<em>how many extra pages:</em><br>
<select name="extrapages" id="extrapages">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select><br><br>
<em>Would you like us to put your site on the internet?</em><br>
<input type="radio" name="sow" id="sow" value="Yes" required="required">Yes
<input type="radio" name="sow" id="sow" value="No" required="required">No<br><br>
<input type="Submit" value="Send!" name="submit">
</form>
Because your form is set to run every time the page loads. You don't check to see if the form from submitted. You also have absolutely no validation.
To fix this wrap all of this code in an if statement that checks to see if the form has been submitted. You can check the $_SERVER
superglobal which contains and key called REQUEST_METHOD
which will tell you if the page was requested via POST (as is common when a form is submitted) or GET (as is common on a "typical" page load). If it's value is "POST" then the form was submitted and you can process the data, if not, ignore that code.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// your code goes here
}