Search code examples
phpemailserver-side

pass variable value between html to php (server side code) mail function


I'm trying to create a contact us form in my website (where I want to send the email without opening mail client window) and for that I got to know that I have to use Server side code for handling the mail() function this is what I found so far :

My form in html page :

<form action="sendmail.php">
                        <input type="text" placeholder="Name" required="">
                        <input type="text" placeholder="Email" required="">
                        <input type="text" placeholder="Subject" required="">
                        <textarea placeholder="Message" required=""></textarea>
                        <input type="submit" value="SEND">
                    </form>

My sendmail.php file (on server side)

  <?php
$to      = 'support.@mydomain.com';
$subject = 'the subject'; // here how can i get the subject 
$message = 'hello'; // here how can i get the message 
$headers = 'From: webmaster@example.com' . "\r\n" . // here 

How can I get the the dynamic values??

    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?> 

So how can I pass the values entered by user on html form as parameter in my php function ??

Update, attempt:

$subject = 'echo htmlspecialchars($_P‌​OST['subject']);';
$message = 'echo htmlspecialchars($_P‌​OST['message']);';
$headers = 'From: echo htmlspecialchars($_P‌​OST['email']);' . "\r\n" . 'Reply-To: webmaster@example.co‌​m' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?>

Error:

Parse error: syntax error, unexpected T_STRING in /home/a9700859/publi‌​c_html/sendmail.php on line 3


Solution

  • You can achieve this using the $_POST method.

    The HTML page.

    <form method="POST" action="sendmail.php">
     <input type="text" name="sender_name" placeholder="Name" required="">
     <input type="text" name="sender_email" placeholder="Email" required="">
     <input type="text" name="subject" placeholder="Subject" required="">
     <textarea placeholder="Message" name="message" required=""></textarea>
      <input type="submit" name="send" value="SEND">
    </form>
    

    Here is your sendmail.php

    <?php
    if($_POST['send'] == 'SEND'){
    
    $to      = 'support.@mydomain.com'; // email where message is sent
    $subject = $_POST['subject']; // here how can i get the subject 
    $message = $_POST['message']; // here how can i get the message 
    $headers = 'From: webmaster@example.com' . "\r\n" . // here how can i get the the dynamic values   
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    
    mail($to, $subject, $message, $headers);
    }
    ?>