PHP
Form skeleton
Build the contact form skeleton with name, email and message fields.
Building the form skeleton
To build the contact form skeleton you write a renderForm() function. This function returns the HTML form as a string, so you can print it with echo anywhere on the page.
The form uses method="post", so the data travels in the request body, not in the URL. Inside you place type="text" (name), type="email" (email), <textarea> (message) and type="submit" (send button) fields. Every field needs a name attribute; PHP reads the value by that name inside $_POST.
Generating HTML with renderForm
renderForm() is a function with a : string return type. Inside, you concatenate single-quoted strings with the . operator. This lets you use double quotes inside the HTML without escaping them.
Example: return '<form method="post">' . '<input type="text" name="name">' . '</form>';. Each line adds one tag; the full string is returned at the end. Then you print the form with echo renderForm();.
Exercise Write the renderForm function
Write a renderForm(): string function. Return a <form> tag with method="post". Inside the form include name="name" (text), name="email" (email), name="message" (textarea) fields and a type="submit" button. On the last line print the form with echo renderForm();.
Show example solution
string { ... }. Inside, concatenate single-quoted strings with . : '<form method="post" action="/contact.php">' . '<label>Name: <input type="text" name="name"></label>' . '<label>Email: <input type="email" name="email"></label>' . '<label>Message: <textarea name="message"></textarea></label>' . '<input type="submit" value="Send">' . '</form>' and return it. On the last line write echo renderForm();.
Example solution:
<?php
// Add the form skeleton
class ContactMessage {
public string $name = "";
public string $email = "";
public string $message = "";
}
function renderForm(): string {
return '<form method="post" action="/contact.php">'
. '<label>Name: <input type="text" name="name"></label>'
. '<label>Email: <input type="email" name="email"></label>'
. '<label>Message: <textarea name="message"></textarea></label>'
. '<input type="submit" value="Send">'
. '</form>';
}
echo renderForm();
Test yourself
-
Which method should the contact form use?
Show answer
POST — Correct. POST carries data in the request body, not in the URL. It fits data like a contact message.
-
Complete the method value in the form tag
'<form method="____" action="/contact.php">'
Show answer
'<form method="post" action="/contact.php">'
-
Match the form elements
- type="text"
- Name box
- type="email"
- Email box
- <textarea>
- Message box
- type="submit"
- Send button
Next lesson: Validating data