How can this method be made more secure in php
if ($_GET['id']){
$id = $_GET['id'];
}
Greetings.
How can this method be made more secure in php
if ($_GET['id']){
$id = $_GET['id'];
}
Greetings.
Let's start by filtering the user's input.
Suppose that valid IDs can only be integers. You can use the filter_var function to accept only this type of data, and avoid entering texts and even SQL commands.
Based on your minimal example, I would add something like this:
if ($_GET['id']){
$id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT));
if( !$id ) { die('Intento de contaminar consulta'); }
// código para procesar Id numérico
}
This is based on the function filter_var returning FALSE
if the filter did not pass , with which you can abort the query, returning or not a message to the user, or process it without that particular data.
But this would only be a first step, as you have been told by others, your question is very broad, you can add many levels of security. The questions you have to ask yourself are more concrete, such as, what do you want to protect? What do you risk if you do not? How much does it cost you? Is the value of the asset to be protected justified for what it costs to do it? And from there you can start in concrete steps, but yes, the validation and filtering of user inputs are basic.
Expanding Jesús Franco's response:
If the id is numeric, it should be enough:
$id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT));
Depending on the situation you can also use the cast to int.
$id = (int)$_GET['id'] // devuelve 0 si id no es númerico o equivalente a
0 , más rápido que intval()
That would be useful if we assume the id is:
An example is the user page: link
The fundamental difference between cast a (int) and filter_var is the cast always returns an int, and filter_var only tells you if it is an int.
If the id is text:
$id= filter_var($_GET['id'], FILTER_SANITIZE_STRING);
More info: link
If you use a text editor in your web application (textarea) it is advisable to pass the HTML Purifier input.
It depends, you can do what Juan says, send that data through POST or follow the recommendations in case of danger of SQL injection.
A basic validation, if it is an integer, is to use the is_int function
$id = null;
if(isset($_GET['id']) && is_int($_GET['id'])){
$id = $_GET['id'];
}