Tạo form liên hệ bằng php

Nếu bạn là người mới bắt đầu lập trình bằng PHP thì đây là một ví dụ đơn giản mà hữu ích dành cho bạn, mình sẽ hướng dẫn các bạn từng bước tạo một form liên hệ cho trang web của mình. Bạn cần làm những việc sau đây : Tạo 2 file lần lượt là contactform.htm và send_form_email.php , kế tiếp là ...

Tạo form liên hệ bằng php

Nếu bạn là người mới bắt đầu lập trình bằng PHP thì đây là một ví dụ đơn giản mà hữu ích dành cho bạn, mình sẽ hướng dẫn các bạn từng bước tạo một form liên hệ cho trang web của mình. Bạn cần làm những việc sau đây :
Tạo 2 file lần lượt là contactform.htmsend_form_email.php, kế tiếp là copy các đoạn code dưới đây và past chúng vào từng file tương ứng.

contactform.htm





Tạo form liên hệ đơn giản


send_form_email.php


"; echo $error."

"; echo "Please go back and fix these errors.

"; die(); } // validation expected data exists if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $comments = $_POST['comments']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= ' Địa chỉ email không hợp lệ.
'; } $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$first_name)) { $error_message .= 'The First Name you entered does not appear to be valid.
'; } if(!preg_match($string_exp,$last_name)) { $error_message .= 'The Last Name you entered does not appear to be valid.
'; } if(strlen($comments) < 2) { $error_message .= 'The Comments you entered do not appear to be valid.
'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below. "; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name: ".clean_string($first_name)." "; $email_message .= "Last Name: ".clean_string($last_name)." "; $email_message .= "Email: ".clean_string($email_from)." "; $email_message .= "Telephone: ".clean_string($telephone)." "; $email_message .= "Comments: ".clean_string($comments)." "; // create email headers $headers = 'From: '.$email_from." ". 'Reply-To: '.$email_from." " . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?>   Thank you for contacting us. We will be in touch with you very soon.

Trong ví dụ này mình sử dụng chức năng hàm mail() mặc định của PHP, nếu các bạn muốn có thể chuyển qua PHP Mailer

Chúc các bạn thành công !

Tags: form liên hệ hoc php php code php tutorial tạo form thu thuat php tự học php

Chuyên Mục: PHP

Bài viết được đăng bởi webmaster