Skip to content
CoursesWeb Forum

How do I handle GET and POST form data safely in PHP?

Staff answerWritten by Callum Iwu · PHP Forms, Sessions and Basics0 replies

Short answer

Read GET data from $_GET and POST data from $_POST, then treat every value as untrusted. Check that it exists, check its type and length, and escape it with htmlspecialchars when you print it in a page. Use POST for forms that change something, and GET for searches and links you want to bookmark.

Written by Callum Iwu · Moderator: PHP, MySQL, Node.js and AI coding tools ·
CiteCoursesWeb Forum, "How do I handle GET and POST form data safely in PHP?", https://coursesweb.net/forum/t/how-do-i-handle-get-and-post-form-data-safely-in-php/, accessed 2026-11-18.
  1. Moderator: PHP, MySQL, Node.js and AI coding tools ·

    A minimal working form

    The HTML first. Each field needs a name attribute, because PHP uses the name, not the id, as the key.

    <form action="contact.php" method="post">
      <label for="name">Name</label>
      <input type="text" id="name" name="name" required>
    
      <label for="email">Email</label>
      <input type="email" id="email" name="email" required>
    
      <button type="submit">Send</button>
    </form>
    

    Now contact.php:

    <?php
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        exit('Please use the form.');
    }
    
    $name = $_POST['name'] ?? '';
    $name = is_string($name) ? trim($name) : '';
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    
    $errors = [];
    if ($name === '' || mb_strlen($name) > 80) {
        $errors[] = 'Enter a name up to 80 characters.';
    }
    if ($email === false || $email === null) {
        $errors[] = 'Enter a valid email address.';
    }
    
    if ($errors) {
        foreach ($errors as $error) {
            echo '<p>', htmlspecialchars($error), '</p>';
        }
        exit;
    }
    
    echo '<p>Thanks, ', htmlspecialchars($name, ENT_QUOTES, 'UTF-8'), '.</p>';
    

    For a search page using GET, the address looks like results.php?q=php&page=2:

    <?php
    $q = $_GET['q'] ?? '';
    $q = is_string($q) ? trim($q) : '';
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) ?: 1;
    
    echo '<h1>Results for ', htmlspecialchars($q, ENT_QUOTES, 'UTF-8'), '</h1>';
    echo '<p>Page ', $page, '</p>';
    

    Why it works

    The PHP manual for $_POST describes it as an array of values sent by HTTP POST with the form content types, and its own example prints a value through htmlspecialchars. $_GET is the same idea for values in the address.

    The ?? operator gives a default when the key is missing, so you do not get an "Undefined array key" warning when someone opens the page directly. filter_input returns null if the field is missing and false if the value fails the check, which is why the code tests for both.

    The htmlspecialchars manual page explains that it converts characters such as <, >, & and quotes into HTML entities. If a visitor types <script> as their name, the page shows the text instead of running it. Escape at the moment you output, using the right escaping for where the value goes.

    GET or POST?

    GET POST
    Where the data goes In the address bar In the request body
    Can be bookmarked Yes No
    Use it for Search, filters, page numbers Contact forms, logins, changes
    Risks Ends up in history and server logs Still needs checking and escaping

    Never send a password or a private token by GET.

    Mistakes beginners make

    1. Trusting the value because the form had required or type="email". That runs in the browser. Anyone can send a request without your form, so validate again in PHP.
    2. Echoing input straight back. echo $_GET['q']; is a classic cross-site scripting hole. Always wrap it in htmlspecialchars.
    3. Putting form values into a SQL string. Escaping for HTML does nothing for SQL. When the value goes into a query, use prepared statements (a thread on them comes next). If your connection code gives errors first, start with What does mysqli_query() expects parameter 1 to be mysqli mean?.
    4. Using $_REQUEST. It mixes GET, POST and cookies, so you lose track of where a value came from.

    Check this in order

    1. Does every input have a name attribute? PHP ignores inputs that only have an id.
    2. Does the form tag say method="post" and the correct action path?
    3. Run var_dump($_POST); at the top of the script to see what really arrived.
    4. If the array is empty, check the browser Network tab: is the request going to the file you expect, and is it a POST?
    5. If you send JSON with fetch, $_POST stays empty. Read the raw body with file_get_contents('php://input'), which the PHP manual notes for other content types. We show the front end side in How do I clear a form after sending it with fetch or AJAX?.

    The CoursesWeb tutorial on PHP GET and POST requests has more examples of reading form data step by step.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.