Reputation: 15984
I have the following php code:
<?php $redirect_lp = $_GET['lp']; ?>
<script>
setTimeout(function(){
window.location.href = "<?php echo $redirect_lp; ?>";
}, 10)
</script>
how do I sanitize $redirect_lp
?
I know this code is bad because of this attack:
http://example.com/index.php?lp="-alert("XSS\n\n"%2bdocument.domain)-"
to protect from this particular attack, I santizie for "
:
$redirect_lp = str_replace("\"", "", $redirect_lp);
is this enough?
Upvotes: 0
Views: 2723
Reputation: 92854
First remove all illegal characters from the $redirect_lp
variable, then check if it is a valid URL:
<?php
$redirect_lp = $_GET['lp'];
// Remove all illegal characters from a url
$redirect_lp = filter_var($redirect_lp, FILTER_SANITIZE_URL);
?>
<?php if (filter_var($redirect_lp, FILTER_VALIDATE_URL)): ?>
<script>
setTimeout(function(){
window.location.href = "<?php echo $redirect_lp; ?>";
}, 10)
</script>
<?php endif; ?>
Upvotes: 4
Reputation: 4795
Basically you need to use the function htmlspecialchars()
whenever you want to output something to the browser that came from the user input.
The correct way to use something like this (enough to prevent XSS-attack):
echo htmlspecialchars($redirect_lp, ENT_QUOTES, 'UTF-8');
After this kind of sanitation that you can validate url (filter_var()
with FILTER_VALIDATE_URL
flag) and allow further steps to redirect user to specified page if validation passed of course.
P.S: You also might want to use strip_tags()
, but keep in mind that it removes tags but not special characters like "
or '
, so if you use strip_tags()
you also have to use htmlspecialchars()
.
Upvotes: 0
Reputation: 5637
There are plenty of ways you can filter a string in PHP. Here's one way to sanitize a URL
:
// Remove all illegal characters from a url
filter_var($redirect_lp, FILTER_SANITIZE_URL);
Or alternatively you can filter the input as you get it:
$redirect_lp = filter_input(INPUT_GET, 'lp', FILTER_SANITIZE_SPECIAL_CHARS);
Upvotes: 1