I have a website in php that does include() to embed the content into a template. The page to load is given in a get parameter, I add ".php" to the end of the parameter and include that page. I need to do some security check to avoid XSS or other stuff (not mysql injection since we do not have a database). What I've come up with is the following.
$page = $_GET['page'];
if(!strpos(strtolower($page), 'http') || !strpos($page, '/') ||
!strpos($page, '\\') || !strpos($page, '..')) {
//append ".php" to $page and include the page
Is there any other thing I can do to furtherly sanitize my input?
Why do we need Input Sanitization? Hackers use RFI (Remote File Inclusion) and injection attacks like Cross-Site Script (XSS) and SQL Injection (SQLi) to exploit the connection between websites and servers. They can execute unauthorized actions that can compromise security.
HTML sanitization is an OWASP-recommended strategy to prevent XSS vulnerabilities in web applications. HTML sanitization offers a security mechanism to remove unsafe (and potentially malicious) content from untrusted raw HTML strings before presenting them to the user.
htmlentities vs htmlspecialcharsBoth will prevent XSS attacks. The difference is in the characters each encodes. htmlentities will encode ANY character that has an HTML entity equivalent. htmlspecialchars ONLY encodes a small set of the most problematic characters.
$page = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['page']);
Is probably the quickest way to sanitize this, this will take anything and make sure that it only contains letters, numbers, underscores or dashes.
Don't "sanitize" - Attacks are specific to the use of data, not the source. Escape values as you output them instead. See also my answer to What’s the best method for sanitizing user input with PHP?
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