PHP with HTML Form

An HTML Form can send values to a PHP webpage.

PHP Form Handling on w3schools.com

The HTML form might look something like this:

<form action="word.php" method="get">
    What is your word?<br>
    <input type="text" name="word"><br>
    <input type="submit" value="GO">
</form>

Notice these three details:

  • action=”word.php” (tells form which file to open when submitted)
  • method=”get” (how the PHP file will receive the data)
  • name=”word” (this exact name will be used in the PHP page)

If one of those is missing, the PHP form will not work properly.

Suppose you have a file called “word.php” that looks like this:

<?php
$word = $_GET['word'];
$len = strlen($word);
echo "Your word is $word.";
echo "$word is $len characters long.";
?>

This webpage expects input data using the GET method.

Visit this php webpage, but add “?word=Potato” to the end of the link in your browser so the address looks a bit like this:

...c9users.io/word.php?word=Potato

This sends a parameter called word with a value of “Potato” as a URL Parameter. Read about sending URL Parameters here.

This should cause the page to display as follows:

Your word is Potato.
Your word is 6 characters long.

The value of the word parameter appears in the HTML output, and PHP also used it to find the length of the name.

If the PHP file works on its own, you are ready to test whether it works with the HTML form. Run the HTML page and submit a name to test it! Make sure the HTML file is in the same folder as the PHP file in your workspace.

Note: PHP could also save the name into a database at this point by opening a mysqli connection and doing an INSERT query.