Form elements (text, text area and password) and PHP

This tutorial explains how to create forms which include a range of form elements include text (textbox), textarea, and password.

  • text – this element is used to get a short amount of text input from the user (a single line)
  • textarea – this element is used to get longer amounts of text input from the user (more than one line)
  • password – this element is used to get password input from a user and will mask any text entered by the user with dots (or asterisks) so that other people cannot see the password

The tutorial will also show how to handle submitted form data using PHP code. Other tutorials have already shown how to use radio buttons and check boxes.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file which will contain the form (eg. form.php) and then copy the following code into it.

  <title>My form</title>

  <form action="action_handler.php" method="POST">
    <p>Username: <input type="text" name="username"> 
      Password: <input type="password" name="password"></p>
    <p><textarea name="comment"></textarea>
      <input type="submit" value="Submit"></p>

Step 2: Create a separate file called action_handler.php which will handle the submitted form data. Copy the following code.

  $username = $_POST['username'];
  $password = $_POST['password'];
  $comment = $_POST['comment'];

  if(empty($username) || empty($password) || empty($comment)){
    echo "You must complete all fields.";
    echo "Hello there, $username.<br/>";
    echo "Thank you for your comment:<br><i>$comment</i>";

Important note

Please note that this tutorial and sample code only explains how to use different form elements including the password element. It does not explain security or encryption when submitting sensitive information such as passwords. It is important to be aware of security and encryption when working passwords and other sensitive data before you publish a website that allows the user to submit this kind of data.

I will discuss some security methods in future tutorials but do not take any responsibility for the security of your own website.