Reading all the posts about sanitizing has left me so confused. I'm creating a blog type of site and need to sanitize user input which will go into a database (user profile information, blog posts, and comments) and certain id's and usernames from GET requests to use queries for information to display.
This is what I've pieced together based on what I've read:
function escape($data) {
global $conn;
connect();
$data = $conn->real_escape_string($data);
$conn->close();
$data = str_replace(chr(0), '', $data);
return $data;
}
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = stripslashes($data);
$data = escape($data);
$data = htmlspecialchars($data);
return $data;
}
The stripslashes confuses me a bit. I know PHP automatically puts those in GET and POST requests and double slashes can be a problem. Should I put addslashes() in the function after stripslashes to make sure it's okay?
For all insert and update statements the inserted values are bound using prepared statements, but all other statements are not prepared (and doing prepared statements on them would not be efficient at this stage in this project for various reasons).
I'd love to get your feedback. Like I said, this is all very confusing!
UPDATE:
I added the $data = str_replace(chr(0), '', $data); to protect against null byte injections. Is that right?
BTW, the only GET requests that go into queries are either ID numbers (which I have a function that removes everything but numbers on) or usernames. I'm using the escape function above to sanitize the username before going into any queries. Is that good enough?
The sanitize function I use on blog posts and profile info which is provided by the user and inserted into a table via a prepared statement.
function cleanInput($input) {
$search = array(
'@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
);
$output = preg_replace($search, '', $input);
return $output;
}
function sanitize($input) {
if (is_array($input)) {
foreach ($input as $var => $val) {
$output[$var] = sanitize($val);
}
} else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = mysql_real_escape_string($input);
}
return $output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With