.htaccess
makes for a poor security layer, especially if someone deploys on nginx instead of Apache. There's nothing preventing someone from visiting /page.php?p=' OR 1=1;--
is there?
Your subsequent clear()
function might be adequate to strip any unwanted characters, but whether or not this is "safe" depends on what the rest of your code does with $p
after you "clear" it.
There are two variants of this question that you might have also meant to ask:
- How to make sure user input doesn't lead to a security vulnerability?
- This is domain-specific, you won't find a one-size-fits-all general solution.
- If you're worried about SQL injection, just use prepared statements and don't worry about what gets passed to the URL.
- If you're worried about XSS, LFI, RFI, etc. then there are other domain-specific security controls you can implement too.
- How to make sure user input is valid.
- Ionizer may be helpful here. It's an open source input filtration/validation library meant to process structured input (multi-dimensional arrays i.e.
$_GET
and $_POST
).
For example, you could do something like this:
<?php
use ParagonIE\Ionizer\GeneralFilterContainer;
use ParagonIE\Ionizer\Filter\{
StringFilter,
WhiteList
};
// Define properties to filter:
$ic = new GeneralFilterContainer();
$ic->addFilter(
'page',
(new StringFilter())
->setPattern('^[A-Za-z0-9_\-]{3,24}$')
);
// Invoke the filter container on the array to get the filtered result:
try {
// $get passed all of our filters.
$get = $ic($_GET);
} catch (\TypeError $ex) {
// Invalid data provided.
}
Now you just have to define your filters and pass the input array ($_GET
, $_POST
, $_REQUEST
, json_decode(file_get_contents('php://input'), true)
, etc.) and you can enforce whatever pattern you want on input strings, or guarantee that certain variables are numeric, etc.