Search code examples
javascriptphpsecurityjavascript-injection

PHP prevent "javascript:" link injection


I'm making a website that allows users to store user preferences in a database, including links.

But i've realised that if a user enters javascript: // Malicious code here they can execute any javascript on the page, including the ability to get session ID's.

( The links are shown to other users, thus I want to prevent this from happening )

I've tried the following things to prevent this but they all don't work:

htmlentities()
htmlspecialchars()
strip_tags()
addslashes()

Quick example of my code:

$link  = // queried from the database.
$title = // queried from the database.

echo '<a href="'. $link .'">'. $title .'</a>';

If you know how I could fix this it would be very much appriciated.


Solution

  • You can test link with FILTER_VALIDATE_URL

    Here is an example

    if(!filter_var($url, FILTER_VALIDATE_URL))
      {
      echo "URL is not valid";
      }
    else
      {
      echo "URL is valid";
      }