Skip to Content
Course content

24: Handling Forms and User Input

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR for a junior developer who had built a simple "Contact Us" form for a client. It looked great and it worked perfectly during his local tests. The problem started the moment it went live. A prankster discovered that the "Name" field wasn't being sanitized and submitted a string of HTML and JavaScript. Every time the client opened their admin dashboard to read the messages, the page would trigger an alert box that said "Hacked!" and then redirect the browser to a YouTube video of a dancing hamster. It wasn't a sophisticated attack, but it was a loud reminder: user input is radioactive. You never, ever trust it.

Choosing Between POST and GET

When you're building a form, your first decision is how to send that data to the server. In PHP, you'll mostly deal with $_GET and $_POST. I like to think of $_GET as "bookmarks." Since the data is appended directly to the URL (like search.php?query=php+tutorials), it's great for search pages or filters. If a user refreshes the page, the data stays there. However, it's terrible for passwords or large amounts of text because URLs have length limits and the data is visible to anyone looking at the browser history.

For everything else—especially anything that changes data in your database, like creating a support ticket or updating a profile—use $_POST. The data is sent in the HTTP request body, making it invisible to the casual observer and capable of handling much larger payloads. Just remember: if you use $_POST and the user hits "Refresh" after submitting, the browser will pop up that annoying "Confirm Form Resubmission" warning. That's a feature, not a bug; it prevents the user from accidentally buying the same product twice.

Cleaning the Mess with Validation and Sanitization

Now, back to the "dancing hamster" problem. To stop users from injecting scripts or breaking your database, you need two different tools: validation and sanitization. I see people confuse these all the time, but they are distinct steps. Validation is asking, "Is this data what I expected?" (e.g., Is this actually an email address?). Sanitization is saying, "I don't care what this is, I'm going to strip out the dangerous parts."

In modern PHP, filter_input() is your best friend. It combines these two concepts beautifully. Instead of accessing $_POST['email'] directly, which can trigger an "Undefined index" notice if the field is missing, use filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL). It returns the cleaned value if it's valid, and false if it's not. It's cleaner, safer, and handles the existence check for you.

// The wrong way: Trusting the user
$email = $_POST['email']; 

// The right way: Validating and cleaning
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

if (!$email) {
    echo "Please provide a valid email address.";
}

Preventing XSS on the Way Out

Here is the golden rule: sanitize on the way in, but escape on the way out. Even if you've cleaned the data before putting it in a database, you should still treat it as dangerous when you echo it back to the browser. This is where htmlspecialchars() comes in. It converts characters like < and > into HTML entities (&lt; and &gt;), meaning the browser will display the code as text rather than executing it as a script.

I've seen developers skip this because they "already sanitized the input." Don't be that person. Different contexts require different escaping. What's safe for a database might not be safe for an HTML page. If you wrap your output in htmlspecialchars(), you effectively kill any XSS (Cross-Site Scripting) attempts in their tracks.

// Even if $username came from a "safe" database, escape it here
echo "Welcome back, " . htmlspecialchars($username, ENT_QUOTES, 'UTF-8');



📋 Practical Task

Build a Secure Support Ticket Submission System

Your task is to create a single-page PHP script that handles a support ticket form. You need to ensure the application is resilient against malicious input and handles errors gracefully.

Requirements:

  • Create an HTML form that collects a Username, an Email Address, and a Priority Level (use a dropdown with options: Low, Medium, High). The form must use the POST method.
  • Use filter_input() to retrieve and validate the email address. If the email is invalid or the username is empty, display a specific error message to the user.
  • Ensure that the "Priority Level" is validated against an array of allowed values (Low, Medium, High) to prevent users from manipulating the HTML to send an unsupported priority.
  • If the input is valid, display a "Success" message that echoes the username and priority level back to the user, ensuring you use htmlspecialchars() to prevent any XSS attacks.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.