0

For a form like this

<form method='post' action=''>
    <input type='url' name='urlink'>
    <button type='submit' name='submit'>Submit</button>
</form>

How to validate any entered URL and be sure that it is safe to be used in the element

<embed>, <frame>, <iframe>, <source>, <img>

What i do is the following steps

<?php 
    $url = $_POST['urlink'];
    $url = filter_var($url, FILTER_SANITIZE_URL);
    $url = preg_replace('#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',"'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $url);

    if(filter_var($url, FILTER_VALIDATE_URL) && preg_match('/(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", $url)){
        echo "SAFE URL";
    } else {
        echo "UNSAFE URL";
    } 
?>

Is that enough for it to be sure that the URL is safe?

glennsl
  • 28,186
  • 12
  • 57
  • 75
AXAI
  • 706
  • 6
  • 17
  • No it's not enough, have a look at [this thread](https://stackoverflow.com/questions/110575/do-htmlspecialchars-and-mysql-real-escape-string-keep-my-php-code-safe-from-inje) for a more extensive solution. – MinistryOfChaps Sep 24 '17 at 18:59
  • Safe URL for what? It clearly depends on what you want to do with the data you receive from the client. – Progman Sep 24 '17 at 19:01
  • @Progman safe to be used in the `elements` i wrote `, , – AXAI Sep 24 '17 at 19:02
  • @MinistryofChaps I use PDO, But my concern is about using the `URLs` inside the HTML `elements`, So i would like to ask, does turning the special characters to HTML entities prevents any special characters from being executed while showing the `elements`? – AXAI Sep 24 '17 at 19:03
  • @AXAI the ticked answer also covers that. – MinistryOfChaps Sep 24 '17 at 19:04

0 Answers0