Full Stack Web Developer (Q1-Q2 2021)

Estimating read time ...
Edited 7th November 2021

HTML Forms and PHP

I’d like us to draw our focus towards creating HTML forms and then processing them with a server-side programming language, which in our case will be PHP. This hopefully should be a relatively straight-forward task.

Forms are one way we can collect data from the user and they can come in various layouts, however they generally consist of a user input (i.e. an input field) and a button for submitting.

We’ll be creating a basic contact form to get us started with building forms today. When we progress onto developing web applications, forms will enable us to build out our application’s complete functionality; for example, if we were to create an e-commerce application, we would need to create a form for merchants to capture the product details, which would include the name of the product, images, size, price and etc.

1. Adding a New Page

Using our project we've continuously committed to Git from the previous sections, let’s start by creating a new PHP page/file called contact.php. Inside the file include your site’s header and footer, then add a new link to your site’s navigation called ‘Contact’ which links to the newly created page.

2. Building Your Form

Creating HTML forms is a simple task but they can eventually become complex once we implement advanced features, such as data inputs over a modal, drop-downs which are dependent on other fields and etc. However, we’ll be sticking to the simplistics.

Please see the guide over at w3schools to setting up forms if you need assistance here, but I will briefly describe some of the foundations.

Following the conventional HTML standards, all elements must contain both an opening and closing tag. For forms, this would be:

<form></form>

All your form data inputs must then be defined inside the tags (i.e. after the opening tag and before the closing tag). For us to be able to read the input data using our server-side programming language, each input must be named. For example, if we are adding an input text field for a username, the following would suffice:

<form> <input type="text" name="username" placeholder="Choose a username."> </form>

In the above example we’ve declared a single user input field, where we have defined the type as text. There are other input types available such as number, where the web-browser will ensure no characters (except numeric) can be added into the field before the form can be submitted. For an exhaustive list of types, please see the w3schools site referenced above.

Additionally we have named the field as 'username' and we will now be able to read the input in our server-side programming language. If we omit the name attribute and value, the data would not be accessible or visible to us. Finally we’ve added a placeholder attribute which is the text inside the input field when the field is blank (this is not a mandatory attribute, but a pleasant optional one).

Ideally, I’d also like you to label all of your input fields. This can be achieved by adding an ID attribute to your input and then adding a <label> element. For example:

<form> <label for="username">Username</label> <input type="text" name="username" id="username" placeholder="Choose a username."> </form>

In the above example we’ve added the id attribute to our previous username field, which identifies the input. We’ve then added a label with the for attribute and the value for this is the given ID name to our input. This then associates the label with the input, so when a user clicks on the form’s label inside their web-browser, the input field is automatically highlighted.

Next, to enable users' the ability to submit the form we must create the submit button. This can be achieved like so:

<button type="submit">Send!</button>

Place this at the bottom of your form after all the inputs, but before the closing </form> tag.

Now finally when the submit button is clicked, we need to identify where the form should be submitted (i.e. where the form data should be sent). We’re going to send this to another PHP file so we can process the inputs from the server-side, this can be achieved by defining the forms' action attribute. Take for example:

<form action="ContactProcess.php"></form>

This would send the form's data to the ‘ContactProcess.php’ file when the user submits the form.

3. Form Fields

Taking the above explanation of HTML forms (you may still need to do additional research), I’d like you to create the following fields for your contact form:

  • Title (e.g. Miss, Mr, Mrs and etc. – this should be a select/drop-down)
  • Full name
  • Residence (UK or Other – this should be a radio option)
  • Email address
  • Subject
  • Message (this should be a textarea)

Please create these forms using vanilla (i.e. barebones) HTML. Do not use Bootstrap for this yet, as I’d like you to experience creating forms yourself in the most simplistic manner before having Bootstrap apply its styling elements.

The above fields (although some are unnecessary in practical use) will give us some experience in building forms with multiple types of inputs. (You may think when should you use a drop-down vs a radio button? I’ve found an interesting read here if you’d want to look more into this.)

4. Server-Side Processing

We will now process our form and handle the user’s inputs but before we can do so, we must first:

  • Create a new PHP file which will perform the processing, e.g. ContactProcess.php. (You may notice we have capitalised letters instead of them all being lowercase and hyphenated, which is the standard rule; however this form of naming is also the standard convention when we advance onto OOP PHP – similar to Java.)
  • Add the file name to your form’s action attribute.

By doing the above your form will now submit data to your newly created PHP file (e.g. ‘ContactProcess.php’). This method of sending data is known as a POST (this is a HTTP method and we’ll cover more when we work with APIs and CRUD principles).

We can now begin processing the form input data. As the data is sent over a POST method, we can access the data in our PHP code using the $_POST variable.

To define a variable in PHP, we can easily do so by adding a dollar sign followed by a name, for example:

$hello = ‘World!’;

This defines the variable $hello with the string value of ‘World!’. Unlike other programming languages, we do not need to define the variable type (e.g. string, object, array etc.) and each statement is ended with a semi-colon.

The $_POST variable is one pre-defined by PHP, which is denoted with the first character of the variable’s name being an underscore. Others such as $_GET also exist.

In your ContactProcess.php file, to start executing PHP code start your first line with:

<?php

Which tells the PHP interpreter you’re writing PHP code and not embedding any HTML inside. (This is the ideal practice of keeping your PHP and HTML code separate, and is the principle followed in MVC standards; again which we’ll move onto when we use the Laravel framework).

Some useful functions for debugging in vanilla PHP code are:

  • die() – Stops the execution of PHP code once this line is interpreted.
  • var_dump() – Prints out the contents of a variable, i.e. variable dump.

You may need to use them in conjunction. For example, you can add the following into your ContactProcess.php file:

die(var_dump( $_POST ));

And once you submit your HTML form, you’ll be redirected to your ContactProcess.php file and you’ll see all the form data printed onto your screen. (For more knowledge on the basics of PHP, please see the w3schools guide.)

At this stage, I’d like you to email the HTML form to yourself. You can do this using PHP’s mail() function (PHP’s manual is a handy site for reference, but you may find other sites such as w3school’s PHP mail() Function site easier to follow, however they only cover basic functions whereas PHP’s manual is exhaustive and more helpful as you advance further).

It is only fair to mention that unfortunately using PHP’s mail() functionality won’t work on your machine as you develop locally, as your machine (which is setup with XAMPP) does not have a mail server and therefore does not have the capability of sending emails. However by simply hosting your code on a webserver, the mail functionality would work; therefore I’d like you to still use PHP’s mail() function for this part of the task. (In the next few sections as we work with APIs, we’ll switch from using PHP’s mail() function to using an email provider via API to complete the functionality).

5. Completing the User Journey

Finally to complete the form’s journey, once you’ve processed the form in PHP I’d like you to redirect the user back to the form with a success message. (Please use Google to research how you can use PHP to redirect a user; this will get you in the practice of learning and figuring out how to achieve the desired functionality using a programming language. Eventually if you continue to practice PHP, you’ll remember how to perform a lot of the programming without needing to search.)

When you redirect the user back, I’d like you to add some parameters into the URL. An example of parameters in the URL are:

http://example.com/contact.php?hello=world&foo=bar&grass=green

In the above example, we denote parameters in the URL by:

  1. Firstly adding a question mark (coloured orange);
  2. We then supply the name (blue) of the key-value pair;
  3. Followed by an equal sign (orange);
  4. And the value (in green).

We can add multiple key-value pairs by adding an ampersand after each key-value pair (denoted in orange). (For security reasons, we never send parameters with values which should be kept confidential, e.g. passwords, payment details and etc.)

By passing in the parameters we can access this method of sending data using PHP once again. The data we passed in as `key-value` pairs from the above example are:

hello => world foo => bar grass => green

I’d like you to pass a simple key-value pair parameter, success => true when you redirect the user back to the HTML form after processing using PHP. This will identify for us that we need to show a success message.

On your contact form page after a successful redirect, you can then use PHP to read the parameter and if true, set a success message/alert using Bootstrap.

When you pass in parameters, as opposed to submitting a form which performs a POST HTTP method, parameters are obtained using GET. You can use $_GET to read any parameters in PHP (using die() and var_dump() on the global variable will again provide some insight, similar to how we did this to $_POST).

Congratulations on making it this far. At this stage we’ve created a simple contact form, which sends the data to PHP (a server-side programming language) for processing where we then email the form to ourselves, and then finally redirect the user back to the form with a success message.

6. Bonus Tasks

As we’ve completed building the form and processing it, we can now advance onto spicing it up a little as optional bonus tasks.

To advance our form a little further, I’d like you to:

Author(s)

Arif Ullah

Developer & CEO