Contact Form

  1. Copy and page our index.php to a new file named about.php , and a new file named contact.php
  2. Change the for each page to reflect its purpose (ie About Us, Contact Me.
  3. Identify the Repeated HTML Problem. To fix the menu across all of our pages, we would have to edit each one individually.
  4. Identify areas of our page that are repeatable. These are areas we can abstract.

We’ve significantly simplified the creation and maintenance of a website as opposed to flat HTML.

  1. Identify the Metadata Problem — Current page has no context (active menu, page title).
  2. Identify the File Organization Problem — Our file paths are hard-coded into every page.

Creating a simple contact form

WARNING — Do not use this code on a live site. This is only for example purposes and is very insecure.*

GET requests are a means of accepting user input that is repeatable, thus sharable, and ultimately visible to the browser’s history.

  1. Ony dynamic portion of URLs is the Query. Proceeded by a question mark ? , the query can contain many key-value pairs, separated by ampersands & .
  2. Open contact.php and add to the .col-sm-8 column.
  3. Visit these example URLs
    • Example: http://localhost:9999/contact.php?some_key=some_value&another_key=another_value Represented in PHP:
Array( [some_key] => some_value [another_key] => another_value ) 
Array( [my_name] => jonathan [my_search] => red birds ) 
  1. action Attribute tells the form what file it should submit to. By default (if no value is given), it submits to the current page.
  2. method Attribute tells the from what type of http request the form will use to submit the data to the server. By default (if no value is given), the method is method=»get» .
  3. Knowing about the defaults, we can tell that this form will submit its values to the contact.php page, using the get request method.
  4. There for, the above html is equivalent to the following html.
form action pl-s">contact.php" method pl-s">get"> form>
form action pl-s">contact.php" method pl-s">get"> Name: input name pl-s">my_name" type pl-s">text"> button type pl-s">submit">Submitbutton> form>
  1. Now when a user visits the contact.php page, they can submit a form that sends the data back to the PHP server.
  2. Add another field where the user can type a bigger message.
form action pl-s">contact.php" method pl-s">get"> Name: input name pl-s">my_name" type pl-s">text"> Message: textarea name pl-s">my_message">textarea> button type pl-s">submit">Submitbutton> form>

Make contact.php send an email.

Читайте также:  Changing CSS

if ( !empty( $_GET ) ) < mail( 'your-real-email-address@example.com', 'Contact form submission from ' . $_GET['my_name'], $_GET['my_message'] ); >
  1. It is not a coincidence that the form method is «get», and the values are stored within the $_GET PHP system variable
  2. Identify the problem with using a GET request with this type of user data. Repeatable, shareable, and browser histories all become liabilities in this case.

Changing the form to send a POST request

POST requests are another way to accept user submitted data, without passing the values within the URL. They are not repeatable, shareable, nor can their values be tracked by the browser history.

  1. Edit the form’s method attribute to the value of post :
  2. Change our debugging PHP to show the values of the $_POST system variable.
  3. Revisit the page, and submit the form with new data. Notice that the data is available to PHP with the $_POST variable, and no longer in the URL.
  4. Adjust our code that sends the email to use the $_POST variable instead of $_GET
if ( !empty( $_POST ) ) < mail( 'your-real-email-address@example.com', 'Contact form submission from ' . $_POST['my_name'], $_POST['my_message'] ); >

Источник

How to Create a Contact Page with PHP

How to Create a Contact Page with PHP

In this tutorial, we’ll be creating a contact page with HTML, CSS and PHP. The code will consist of an HTML form, validation, and PHP code that will process the form data.

The Advanced package includes additional features and a download link to the source code.

What is a contact page used for?

When a user visits your website, they can use the contact page to contact you regarding many aspects of your website. For instance, the user could report a bug, or they could give you their unbiased feedback. Whether their intentions are good or not.

In addition, the contact page can help you with marketing opportunities and will provide a way to communicate with your audience.

Contents

1. Getting Started

Before we start coding our contact form, we need to ensure we have a working web server and meet all the requirements below. We cannot execute PHP code without a working web server as it is a server-side programming language.

1.1. Requirements

  • Web Server — If you haven’t installed a local web server solution package, I recommend you download and install XAMPP. XAMPP is an open-source web server solution package.
  • Mail Server (SMTP) — Without a working mail server, you’ll unable to receive emails that are processed using the contact form. If you’re hosting your website with a provider, you shouldn’t need to do anything. However, if you have your own server (dedicated/vps), I recommend you install Postfix.

1.2. What You Will Learn in this Tutorial

  • Design a Contact Form — We’ll be using CSS to design our contact form and HTML to structure our code.
  • Form Validation — Implement validation to individual elements in our form.
  • Send Mail — The PHP mail function will enable us to send mail to a specified email address.

1.3. File Structure & Setup

We will now start our web server and create the files and directories we’re going to use for our contact form page.

  • Open the XAMPP Control Panel
  • Next to the Apache module, click Start
  • Next to the MySQL module, click Start
  • Navigate to XAMPPs installation directory (C:\xampp)
  • Open the htdocs directory
  • Create the following directories and files:

File Structure

\— contactform
|— contact.php
|— style.css

The above files and directories will contain the following:

  • contact.php — This file will contain our contact form template and PHP code that will process the form.
  • style.css — The stylesheet that will structure our page and make it look more appealing.

2. Designing the Contact Form with CSS

The stylesheet will structure our layout and describe how each element will display on the screen. It includes the fonts, colors, and size of the elements.

Edit the style.css file and add:

html, body, div, input, span, a, select, textarea, option, h1, h2, h3, h4, main, aside, article, section, header, p, footer, nav, pre < box-sizing: border-box; font-family: Tahoma, Geneva, sans-serif; >html < background-color: #F8F9F9; padding: 30px; >input,textarea,p < outline: 0; >h1 < margin: 0; padding: 20px; font-size: 22px; text-align: center; border-bottom: 1px solid #eceff2; color: #6a737f; font-weight: 600; >.contact < background-color: #fff; width: 500px; margin: 0 auto; box-shadow: 0px 0px 5px 0px rgba(0,0,0,.2); >.contact .fields < position: relative; padding: 15px; >.contact input[type="text"], .contact input[type="email"] < display: block; margin-top: 15px; padding: 15px; border: 1px solid #dfe0e0; width: 100%; >.contact input[type="text"]:focus, .contact input[type="email"]:focus < border: 1px solid #c6c7c7; >.contact input[type="text"]::placeholder, .contact input[type="email"]::placeholder, .contact textarea::placeholder < color: #858688; >.contact textarea < resize: none; margin-top: 15px; padding: 15px; border: 1px solid #dfe0e0; width: 100%; height: 150px; >.contact textarea:focus < border: 1px solid #c6c7c7; >.contact input[type="submit"] < display: block; margin-top: 15px; padding: 15px; border: 0; background-color: #518acb; font-weight: bold; color: #fff; cursor: pointer; width: 100%; >.contact input[type="submit"]:hover < background-color: #3670b3; >.contact input[name="email"] < position: relative; display: block; >.contact label < position: relative; >.contact label i < position: absolute; color: #dfe2e5; top: 31px; left: 15px; z-index: 10; >.contact label i ~ input < padding-left: 45px !important; >.contact .responses

That’s all we need to do for the stylesheet file. You are free to customize it to your liking.

3. Structuring the Contact Form with HTML

Now, we need to structure our page and implement the contact form and its elements.

Edit the contact.php file and add:

Contact Form

That will create our template and all the fields we’ll associate with our contact form. As you can see in the head section, we have included our stylesheet file along with the FontAwesome library, which will enable us to use icons in our form.

We’ll be using a POST request to process the form and therefore the form’s method is set to post. As the form data will be processed in the same file, there is no need to specify the action value. Instead, we can leave it blank.

The contact form consists of the following elements:

This will create the email field. We have declared the name attribute as this is what we’ll use when retrieving the data with PHP, which can be retrieved with $_POST[’email’].

The above element will create our name field, which will be the user’s real name.

The above element, will be our subject field, which is basically the title of the message.

Finally, we have the message field. The textarea element is different from the others we have declared as it will enable the user to write on multiple lines as opposed to just the one.

Have you noticed how we have specified the required attribute on all our form elements? That’s because the browser will validate the form before submission, which can help prevent multiple submissions to our server.

If we navigate to our new file in our browser, we should see:

PHP Contact Form

That’s all we need to do for this part. We have designed and structured our contact form. Next, we’ll start coding the PHP aspect.

4. Processing the Contact Form with PHP

We can finally start coding our contact form with PHP. In this section, we’ll validate the form fields and send mail directly to an email address.

Edit the contact.php file and add the following code at the very top, before the template code:

 // Make sure the form fields are not empty if (empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['name']) || empty($_POST['msg'])) < $responses[] = 'Please complete all fields!'; >// If there are no errors if (!$responses) < // Where to send the mail? It should be your email address $to = 'contact@example.com'; // Send mail from which email address? $from = 'noreply@example.com'; // Mail subject $subject = $_POST['subject']; // Mail message $message = $_POST['msg']; // Mail headers $headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $_POST['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // Try to send the mail if (mail($to, $subject, $message, $headers)) < // Success $responses[] = 'Message sent!'; >else < // Fail $responses[] = 'Message could not be sent! Please check your mail server settings!'; >> > ?>

First, we declare a variable that will output all the responses in our form, whether it will be an incorrect email response or something else.

Subsequently, we check if the form was submitted by checking if the post variables exist, which is what the isset() function will do for us.

Finally, if there are no validation errors, the code will try to send the mail to the specified email address. Make sure to update the $to variable.

Now we need to add the responses variable to our form. Find the following line:

That’s all we need to do to create a contact form. If you encounter a mail server error, you will need to verify your mail server settings and make sure they’re correct.

Conclusion

Congratulations! You’ve successfully created a contact form with HTML, CSS, and PHP. What next? Consider implementing your own validation and extend the contact form to support more fields, such as category, priority, etc.

Consider sharing the article on social websites if you’ve found it helpful and drop a comment below. We greatly appreciate the support.

Enjoy coding and thank you for reading!

If you would like to support us, consider purchasing a package below. It will greatly help us create more tutorials and keep our server up and running. Packages include improved code and innovative features.

Источник

Оцените статью