Checking user input link syntax

I have a website where users can enter comments and descriptions. I also allow them to enter links. I use strip_tags with an exception for links. I also add rel="nofollow" through a simple string_replace.

The problem is that if users leave a double quote at the end of their opening tag, it will ruin the html. Any suggestions on how to check or correct invalid link syntax?

$comment = $_POST['comment'];
$comment = strip_tags($comment,"<a>");
$comment = str_replace('<a','<a rel="nofollow"',$comment);
$comment = mysql_real_escape_string($comment);

and upon withdrawal

$ comment = stripslashes ($ comment);

echo $ comment;

The problem is that users add <a href="www.blah.com> and forget the last double quote, this ruined the way the comment is displayed.

+6
source share
1 answer

Here is what you need to do:

 function fixLink($link) { $link = str_replace(array('<a', '"', '</a>'), '', $link); $link = str_replace( array('=', '>', ' '), array('="', '">', '" '), $link); return '<a rel="nofollow' . $link . '</a>'; } echo fixLink('<a href="/index.html>asd</a>') . "\n"; echo fixLink('<a class="awesome" href="/index.html>asd</a>') . "\n"; echo fixLink('<a href="/index.html class="awesome">asd</a>') . "\n"; echo fixLink('<a target="_blank" href="/index.html class="awesome">asd</a>') . "\n"; echo fixLink('<a target="_blank" href="/index.html class="awesome>asd</a>') . "\n"; echo fixLink('<a target="_blank" href="/index.html target="_blank" class="awesome">asd</a>') . "\n"; echo fixLink('<a href="/index.html class=awesome">asd</a>') . "\n"; 

This will output:

 <a rel="nofollow" href="/index.html">asd</a> <a rel="nofollow" class="awesome" href="/index.html">asd</a> <a rel="nofollow" href="/index.html" class="awesome">asd</a> <a rel="nofollow" target="_blank" href="/index.html" class="awesome">asd</a> <a rel="nofollow" target="_blank" href="/index.html" class="awesome">asd</a> <a rel="nofollow" target="_blank" href="/index.html" target="_blank" class="awesome">asd</a> <a rel="nofollow" href="/index.html" class="awesome">asd</a> 
+5
source

Source: https://habr.com/ru/post/896174/


All Articles