Explain Codes LogoExplain Codes Logo

When submitting a GET form, the query string is removed from the action URL

html
form-submission
xss
query-strings
Anton ShumikhinbyAnton Shumikhin·Aug 15, 2024
TLDR

Submit a GET form without losing query strings in the action URL by embedding them as hidden fields. Here is an example:

<form action="http://example.com" method="get"> <input type="hidden" name="fixedParam" value="fixedValue" /> <!--Fixed value, much like my dedication to StackOverflow --> ... <input type="submit" /> <!--Here we go! --> </form>

This method ensures both static and user-input parameters exist in the URL after submission.

Ensuring effective GET form submission

Embed query strings inside hidden form elements

When using GET for form submission, any pre-existing query string in the action URL might be removed due to browser behaviour. To counter this, use hidden input fields:

<form action="http://example.com/results" method="get"> <!-- Assume original URL had ?search=html&filter=recent --> <input type="hidden" name="search" value="html" /> <!--Keep calm, search is here--> <input type="hidden" name="filter" value="recent" /> <!--I filter out the bad puns --> <!-- Add other form elements --> <input type="submit" /> <!--Press to impress --> </form>

Security first – Better safe than sorry

To avoid XSS (Cross-Site Scripting) attacks, escape parameters before outputting them in hidden form fields. In PHP, use htmlspecialchars():

<?php $value = htmlspecialchars($_GET["param"], ENT_QUOTES, 'UTF-8'); //Looks scary, but you can trust me echo "<input type='hidden' name='param' value='${value}' />"; ?>

Server-side script for decoding URL parameters

Ensure your server-side code can decode URL-encoded query strings. Use http_build_query() for managing arrays, and explode() for extracting query params and creating hidden form inputs in PHP.

Detailed Notes on GET forms

Form data-set appended to action URL

In an HTML5 standard-compliant browser, form data-set is appended to the action URL. So, the initial query string may disappear.

Percent-Encoding special characters

If your action URL needs to include a question mark and other special characters, percent-encode the URL. This way, browsers interpret your URL as you intended. Minimal use of percent-encoding can help maintain cleaner URLs.

Query strings in POST metbod

A form submitted using a POST can have a query string in its action URL. POST method sends data in the body of the request, not the URL.

Watch out for these!

  • 👀 Browsers might discard query strings: Avoid relying solely on the browser to keep the query string in the action URL.
  • 🐞 Assumptions in server-side scripts: Your scripts should work irrespective of query parameters' presence directly in the URL or in hidden form fields.
  • 🛡️ Security quirks: Always escape parameters to prevent XSS attacks, no matter where the data comes from.