title: How do I sanitize a user submitted url?
body: <p>I want to store users' personal urls as plain text, encoded by htmlspecialchars().</p>
  
  <p>Then I would retrieve this data and generate and display a link, as follows:</p>
  
  <pre><code>echo '&lt;a href="'.$retrieved_string.'" target="_blank"&gt;';
  </code></pre>
  
  <p>And yet, even with encoded special chars and quotes, the href may not be safe, due to the potentially inserted javascript, example of a bad link:</p>
  
  <pre><code>javascript:alert(document.cookie);
  </code></pre>
  
  <p>So what I'm thinking is to strip up for a potential 'javascript' tag (before I do the special chars encode of course), as follows:</p>
  
  <pre><code>preg_replace('/^javascript:?/', '', $submitted_and_trimmed_input);
  </code></pre>
  
  <p>So let us sum it up altogether:</p>
  
  <pre><code>$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 '&lt;a href="'.$a['link'].'" target="_blank"&gt;';
  </code></pre>
  
  <p>Now the question is, would it be enough to an url link safe, or is there any other potential surprises I should be alert against?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I've read a bit about filter_var() and it seems to utterly fail in many ways. It doesn't validate international domains with unicode chars, then again the following string successfully passes the test: </p>
  
  <pre><code>http://example.com/"&gt;&lt;script&gt;alert(document.cookie)&lt;/script&gt;
  </code></pre>
  
  <ul>
  <li>I mean common... that's just rediculous, there must be a better way</li>
  </ul>