Paradoxis
Paradoxis

Reputation: 4708

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.

Upvotes: 2

Views: 1275

Answers (3)

Mike Samuel
Mike Samuel

Reputation: 120576

You should whitelist URLs by protocol. There are too many ways to obfuscate javascript: by varying case, inserting NULs, BOMs, space characters, etc. for a simple test to reliably identify all javascript: URLs.

If you want to allow only URLs with protocol

  1. http
  2. https
  3. mailto
  4. tel

then you can test your input against a regex like

/\A(?:https?:\/\/|mailto:|tel:|[^:]*(?:\/|\z))/i

which will pass any URL that has one of the protocols above, and any relative (or protocol relative) URL that does not have a colon before the first /.

Upvotes: 2

Ali Akbar Azizi
Ali Akbar Azizi

Reputation: 3516

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";
  }

Upvotes: 3

jcaron
jcaron

Reputation: 17720

You'll need to test the links, probably with a regular expression, possibly '^https?://'

Upvotes: 1

Related Questions