2
Docs2
2
$Painfree->safe()
$Painfree->safe(string $unsafe) : string
$Painfree->safe(string $unsafe) : string
This function is designed to provide a starting point for user-input web safety. It's primary purpose is to provide an HTML escaping mechanism for any user-submitted code that you want to render inside of a template.
public function safe($unsafe='') : string {
// null arguments to htmlspecialchars() is deprecated
if ( ! $unsafe ) {
return '';
}
return htmlspecialchars($unsafe);
}
Use this function (or something like it) anywhere you're going to be showing user-provided input in your HTML templates. This function is the bare minimum you'd need to prevent XSS attacks.
This function is just a starting point for safely handling
user input. It's merely a thin wrapper around
htmlspecialchars()
. You
should consider your application's security requirements
on a case-by-case basis and write code accordingly.
<?php
$user_input = 'Title<script>alert("hello");</script>';
?>
<div id="post-title" class="bg-dark text-light">
<?= $user_input_title; ?> <!-- alerts -->
</div>
<div id="post-title-escaped" class="bg-dark text-light">
<?= $Painfree->safe($user_input); ?> <!-- doesn't alert -->
</div>
<div id="post-title" class="bg-dark text-light">
Title<script>alert("hello");</script> <!-- alerts -->
</div>
<div id="post-title-escaped" class="bg-dark text-light">
Title<script>alert("hello");</script> <!-- doesn't alert -->
</div>