简体   繁体   中英

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.

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

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 / .

您可能需要使用正则表达式(可能是'^https?://'来测试链接'^https?://'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM