How to sanitize / clean HTML characters and entities in PHP? [closed]

-3

I would like to sanitize the user input in a form with PHP to prevent the user, for example, from writing < , > since the input is what is written in the HTML document ...

The user, in the field, must type the URL (link) that he wants to shorten, so I need the code so that the POST deletes characters such as < , or that are not from a URL.

    
asked by Pancho 22.03.2017 в 18:50
source

4 answers

2

You can use htmlspecialchars () htmlspecialchars - Convert special characters to HTML entities

<?php
$nuevo = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $nuevo; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

I imagine that strip_tags () can also serve you. strip_tags - Remove HTML and PHP tags from a string

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other     text</a>';
echo strip_tags($text);
echo "\n";

// Permite <p> y <a>
echo strip_tags($text, '<p><a>');
?>

The result of the example would be:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
    
answered by 22.03.2017 в 19:20
1

With javascript, it's just having the codes you do not want to include and validating them. Ex:

 <script>
 function noCharacter(evt) {
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 58 && charCode < 65)
    {
        alert('Caractér no valido');
    }
 return true;
 }
 </script>
 <body>
 <input type="text" id="a" name="a" onkeypress="noCharacter(event);" />
 </body>
    
answered by 22.03.2017 в 19:40
0

If you want to remove the characters (< >) you can do it using str_replace

Official Documentation

Ex:

 $url = $_POST['url'];
 $search = array("<",">");
 $url = str_replace($search,"", $url);

Php pose a function to filter the variables, which also filters the URL I leave the example:

Official Documentation

$url = $_POST['url'];    
$url = filter_var($url, FILTER_SANITIZE_URL);
    
answered by 22.03.2017 в 19:10
0

The FILTER_SANITIZE_URL filter removes all url characters that are illegal from a string.

This filter allows all letters , digits and $ -_. +! * '(), {} | \ ^ ~ [] "> <#%; /?: @ & =

Example:

//Obtenemos URL mediante POST.
$url = $_POST['url'];

//Salida url.
var_dump(filter_var($url, FILTER_SANITIZE_URL));

PHP Manual - filter_input ()
w3schools

Another option would be to use the filter_var function, Filter a variable with the indicated filter.

<?php
//Obtenemos URL mediante POST.
$url = $_POST['url']; 

//Comprobamos validez URL.
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
    echo("$url es una URL valido");
} else {
    echo("$url no es una URL valido");
}
?> 

Manual - PHP filter_var ()

    
answered by 22.03.2017 в 20:40