Search code examples
phphtmlemailsubscription

HTML PHP email submit form


I'm trying to create a PHP form that allows users to insert their email address and it automatically sends me an email with their email address. something like a subscription.

what I have so far is this:

<form  action="" method="post">
    <input type="email" name="email" placeholder="Enter your email address" /><br>
</form>

I found this PHP sample that I believe answers my problem, but I have no idea how to call it from my HTML.

<?php
if(isset($_POST['email'])){
$email = $_POST['email'];
$to = 'myemail@something.com';
$subject = 'new subscriber';
$body = '<html> 
            <body>
                <p>Email:<br>'.$email.'</p>
            </body>
        </html>';
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset-utf-8";

$send = mail($to, $subject, $body, $headers);
if($send){
    echo '<br>';
    echo 'thanks';
}else{
    echo 'error';
}
}
?>

Solution

  • There's insufficient code for me to be able to answer completely, but the one thing that comes immediately to my mind is not leaving action="" empty. Try $_SERVER['PHP_SELF'] variable, it should print the path to the file that is currently running so you'll be presented with the same page, but with data in $_POST you'll send. You can try it like this:

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <input type="email" name="email" placeholder="Enter your email address" /><br>
    </form>
    

    If you wish to send data to the same file like this, please make sure your PHP code is in the same file as the HTML structure of your form. It may make things easier if you put your PHP code first, so you can exit; from the file (not displaying the form anymore) telling the user that the message has been sent or that the error has occured.