I'm wondering how safe it is to use this code. Especially the $_SERVER['REMOTE_ADDR']
and $_SERVER['HTTP_USER_AGENT']
I've been doing some research on this. As far as I can tell it should be safe to just compare the variables like I do here? I should only worry about their values when using them to run sql queries or when displaying their content on my pages?
Depending on where I use them I should run mysqli_real_escape_string
or htmlspecialchars
.
When should I use the trim
or stripslashes
functions?
I'm just trying to protect my website from being hacked in the most obvious/common ways. Doesn't require huge protection, but I'd like it to be at least decently secure!
Anything I'm overlooking or doing wrong? Are there any guide that explain most of this?
session_start();
if (!isset($_SESSION['logged_in'])) {
$_SESSION['logged_in'] = false;
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : '';
} else {
if ($_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR'] || ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT'])) {
session_destroy();
header('Location: view/index.php');
die();
}
}
$_SERVER['REMOTE_ADDR']
is created by the webserver, it's safe and reliable. It's always just an IP address in numeric format, you don't need to sanitize it.
$_SERVER['HTTP_USER_AGENT']
comes from the client, and it can contain anything. If you're going to store it in the database or display it, you need to treat it like any other user-supplied input.