How to secure get request in php

What's the best way to secure a GET request or are there any, safer alternatives?


I'm using a couple of GET requests in my website to generate webpages dynamically and to delete records based on ID.

The last one worries me a bit, because people could just change the URL to whatever file they want to delete.

To have access to the delete-file they do need to login and have certain permissions, which will throw an error if they don't have sufficient permissions.


I came across a really old SO post, stating that you should use themysqli_real_escape_string function to make it at least more secure.

I also read about validation being really important, so I was thinking about checking whether the ID is an actual integer or not.

There's another post stating that hiding the request in the URL is basically useless, since the request will always be a part of the URL.


This is my delete-file, it uses two statements, one deletes the actual post, and the other one deletes the associated images with that post.

include('./utils/auth.php');

require('./utils/db.php');

$stmt_1 = $connect->prepare('DELETE FROM `dias` WHERE diaserie_id = ?');

if($stmt_1) {
    $id = $_GET['id'];
    $stmt_1->bind_param('i', $id);
    if($stmt_1->execute()) {
        // Als de afbeeldingen uit de database zijn, verwijder dan ook de serie zelf
        $stmt_2 = $connect->prepare('DELETE FROM `diaseries` WHERE diaserie_id = ?');
        if($stmt_2) {
            $stmt_2->bind_param('i', $id);
            if($stmt_2->execute()) {
                echo "Both the files and post have been deleted.";
            } else {
                echo "The files have been deleted, the post iself could not be deleted.";
            }
        }
    } else {
        echo "Files and post could not be deleted.";
    }
}

This post is also available in the following languages: Portuguese.

In this article, we will cover two request methods: the GET and the POST methods, for sending and receiving data from an HTML form using PHP. Also, we will examine the most common problems involving information security, such as Cross-Site Scripting (XSS) and SQL Injection, and how to solve them with adequate sanitization.

Let's start with the theory: what are GET and POST requests, and how do they differ? – if you want to, you can skip to the next section, where we will start with the practice.

Understanding the GET and POST methods

The Hypertext Transfer Protocol (HTTP) was developed as a protocol to serve the transmission of documents, and works as an intermediary between internet browsers and web servers. You are used to reading it in the addresses of web pages – as well as its “brother”, the HTTPS, a more secure encrypted version (hence the “S” at the end, meaning “Secure”).

In other words, HTTP is a protocol that serves as a “bridge”: it collects a request from the internet browser; sends it to the server; waits for an answer; and, finally, it returns the new information to the browser.

Generally, these requests keep some metadata in their “header”, that contains messages used to perform certain behavior on the client or on the server. In addition, HTTP requests can assume different models.

The most used HTTP request types are GET and POST, but there are other types in their technical specification, such as PUT, HEAD, DELETE, PATCH and OPTIONS. For the purposes of this article, we will focus only on the two most common.

The GET request

The GET request method is used when you want to obtain data from a specific source or resource. It should only be used to retrieval data, because its query string are sent and displayed at URL, for example: https://www.youtube.com/watch?v=fJ9rUzIMcZQ&t=3m5s.

When we insert this URL into the browser, we are asking the YouTube server for a specific resource: to retrieve the data from the video v identified as fJ9rUzIMcZQ. As soon as the server “returns” the request, the HTTP protocol will tell the browser how to display the video, in this example, the official video for the song “Bohemian Rhapsody”, by the British band Queen.

Note that in our example, the second parameter of the GET request, the t parameter, informs the start time that we expect in our response, in this case, from 3min and 5s. The parameters v and t are separated by the character &, which indicates to the HTTP protocol where the “key-value” pairs of these parameters begin and end. So, the server knows exactly that you search for the video v=fJ9rUzIMcZQ at the time t=3m5s.

GET requests are generally limited in length — for most browsers, it is up to 8 KB, or 8192 bytes in URI — and, because they only serve to request data, they are not able to modify it. In addition, they can be stored in cache, in the browser's history and also in the bookmarks. That's why you should never use it to send sensitive data, such as Social Security Numbers and user passwords.

💡 Some developers, however, ignore it and expose personal and sensitive data of people on the internet. In Brazil, due to the General Personal Data Protection Law (LGPD), this practice may cause big inconveniences, such as serious penalties to the company or to the ones who operate and manage this data, when a leak happens. So, the best practice is to never send sensitive personal data via the GET method.

The POST request

The POST request method is used to send data to the server, to update or create a new resource.

Unlike the GET method, the POST method does not expose the information at the URL address. In this case, the data is transmitted in the HTTP request body, as follows:

POST /update/webform.php HTTP/1.1
Host: youtube.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 42
user=Stevie&playlist=British&v=fJ9rUzIMcZQ

In this example, we are informing the Host: youtube.com server that we will make a POST method request to the /update/webform.php address, using the technical specifications of the HTTP/1.1 protocol. We are also indicating that there is a 42 character information (Content-Length: 42), in the standard Content-Type content format, whose value is application/x-www-form-urlencoded. Finally, our information is on the bottom line, containing 3 parameters: user, playlist, and v.

💡 The information traveling in the body of the HTTP request can be intercepted by bad agents. The best practice, then, is to make these transmissions using encryption, via the HTTPS protocol, so it makes harder to them read this information.

Let's assume the YouTube server recognized our request, and this address is valid. In our example, the informed video, which we received previously, will be added to the British playlist of the user identified as Stevie.

Note that this is a one-time request, which is unlikely to be repeated. As a rule, the POST method, unlike GET, is not stored in cache or in the client's browser history, nor can it be saved in bookmarks. POST requests have no restrictions on the size of messages, which allows us to send complete articles, such as this one, through an electronic HTML form, for example. Also, the POST method supports a wide variety of Content-Types, including binary documents, strings, and numbers.

💡 POST method is generally preferable over GET. However, there are situations in which we should include the requisition data in the address URL: for example, in search forms or by displaying documents and videos, because we want the client to be able to repeat it easily and to re-access the address through the browser's history.

Creating forms with HTML and PHP

Now that we understand how the GET and POST methods work in the theory, let's go to the practices: let's create an HTML form, and have it to send and to receive information using PHP.

💡 There are several ways to do this, like via JavaScript and AJAX, where the user don't have to refresh the page, because we are transmitting the information asynchronously. For the purposes of this article, we will focus only on HTML and PHP technologies.

Inserting the form on the page

The first step to create our web page is to inform the structure of the

element that will contain the fields where user types the data, like this:


<form method="GET" id="webform" name="webform" action="target.php">
form>

In this fragment, we are using the GET method, defined in method="GET", to send the information that will be inserted into the form, whose name was defined in name="webform", to the target page (action="target.php").

Inserting the fields to the form

The next step is to insert the fields, or inputs to our form, where users can type the values. Let's update our source file like this:


html>
<html>
<head>
    <meta charset="utf-8">
    <title>Electronic formtitle>
head>
<body>
    <form method="GET" id="webform" name="webform" action="target.php">
        <label for="iduser">User ID:label>
        <input type="text" id="iduser" name="iduser"> <br />

        <label for="idplaylist">Playlist ID:label>
        <input type="text" id="idplaylist" name="idplaylist"> <br />

        <label for="v">Video ID:label>
        <input type="text" id="v" name="v" value="fJ9rUzIMcZQ"> <br />

        <button type="submit">Send databutton>
    form>
body>
html>

We inserted 3 fields, defined by the HTML tag , and also 1 button that sends the form's data, using