How to clear custom URL?

I want to store user personal URLs as plain text encoded by htmlspecialchars ().

Then I would extract this data and generate and display a link:

echo '<a href="'.$retrieved_string.'" target="_blank">'; 

And yet, even with encoded special characters and quotation marks, href can be insecure due to the potentially bad javascript inserted of the bad link example:

 javascript:alert(document.cookie); 

So, I think we need to break the potential javascript tag (before I, of course, encode special characters), as follows:

 preg_replace('/^javascript:?/', '', $submitted_and_trimmed_input); 

So to summarize:

 $input=htmlspecialchars(preg_replace('/^javascript:?/', '', trim($_POST['link'])),11,'UTF-8',true); mysql_query("update users set link='".mysql_real_escape_string($input)."'"); //And retrieving: $query=mysql_query("select link from users"); $a=mysql_fetch_assoc($query); echo '<a href="'.$a['link'].'" target="_blank">'; 

Now the question is, is there enough link for the link to the URL, or are there any other potential surprises that I should be warned about?

EDIT:

I read a little about filter_var () and it seems to completely fail in many ways. It does not check international domains with unicode characters, then again the line passes the test successfully:

 http://example.com/"><script>alert(document.cookie)</script> 
  • I mean general ... it's just funny, there must be a better way
+7
source share
2 answers

This is how I do it. I think the best way is to add it using http:

 $link=preg_replace('/^(http(s)?)?:?\/*/u','http$2://',trim($_POST['website'])); 

So even if the script gets there, I don’t care. Then actually convert the characters:

 $link= htmlspecialchars($link, 11,'UTF-8',true); 

What is it. There is no beating around the bush, and should be compatible with utf-8.

-2
source

Try using filter_var()

 filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) 
+9
source

All Articles