How to make a email / feedback form in php

php

In this article I will guide you to create a simple email form using html and php. The form is created using html and the mail is sent using php code.

Let’s take a brief look at php mail() function

The mail() function is used to send email from a web page in php.
Syntax : mail(to,subject,message,headers,parameters);

where :

ParameterDefenition
tospecifies the email of the recipient (required)
headersspecifies additional headers like From, Cc, and Bcc etc. (optional)
messagemessage to be sent (required)
parametersspecifies additional parameters (optional)
subjectsubject of the email (required)

Create a new file named mailform.php and copy all the code below to the file. You can customize this example according to your web design.

Note! This example will not work on ‘localhost’ WampServer or XAMPP. It works only on a real web server. So upload this file to your blog or web server to see the results.

<!DOCTYPE html>
<html>
<head>
<title>Email form example</title>
</head>
<body>

    <form method='post' action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
        <input type='text' name='name' placeholder='Name'>
        <br><br>
        <input type='email' name='email' placeholder='Email'>
        <br><br>
        <textarea rows='4' cols='80' name='message' placeholder='Messsage'></textarea>
        <br>
        <input type='submit' value='submit'> 
    </form>


    <?php

    $email_to = 'yourmail@gmail.com'; //Enter your email address
    $subject = 'yoursubject';

    $name=$email_from=$message="";
    if(isset($_POST['name']) && !empty($_POST['name'])) {
        $name = $_POST['name']; //get name
    }
    if(isset($_POST['email']) && !empty($_POST['email'])) {
        $email_from = $_POST['email']; //get from email address
    }
    if(isset($_POST['message']) && !empty($_POST['message'])) {
        $message = $_POST['message']; //email message to be sent
    }

    $headers = 'From: '.$email_from."\r\n". //header part of the email, from, reply to etc..
    'Reply-To: '.$email_from."\r\n" .
    'X-Mailer: PHP/' . phpversion();

    if(($message!="")&&($name!="")&&($email_from!=""))
    $ok = mail($email_to, $subject, $message, $headers);  //function to send email

    if($ok) {
        echo "Email sent successfully";
    }

    ?>

</body>
</html>

Output of above example