简体   繁体   中英

Escaping special characters in javascript in a link

Not sure if I'm asking the right question. But this is what I want: I have this code:

$content = rawurlencode(file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file));
$thelist .= "<li class=files><a href=javascript:alert('".$content."') class=filelink>".$file."</a></li>";
echo $thelist;

What I want is to alert (actually this is just a test, I want to use the $content as argument in a function) the $content when I click the link. How should I do this?

I'm guessing it would work fine if the file is a simple txt file. But the file I'm using here is a C++ program, which contains characters <>, obviously

First you need to get the file contents. This is pretty straight forward, except that you need to make sure that $user and $file don't contain any unexpected characters, such as "../" that would take you outside of the designated directory. Example using preg_match() :

if (!preg_match ('/^[\w\d]+$/', $user) ||
    !preg_match ('/^[\w\d]+$/', $file)) {
  /* Error */
  return;
}
$content = file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file);

Next, you need to turn the contents into a valid javascript string. To do this, you need to escape the backslash , double or single quote and line terminator characters (including U+2028 and U+2029 ). I believe the easiest way to do this is using json_encode() :

$code = json_encode ($content);

The code (after the javascript: part) is technically a URL so it has to be escaped with rawurlencode() :

$href = 'javascript: ' . rawurlencode ("alert ($code)");

The href (and also the file name) then needs to be suitably escaped with htmlspecialchars() to be used as an HTML attribute. I think this can actually be skipped for $href because the string is HTML-safe after rawurlencode()

$href_h = htmlspecialchars ($href);
$file_h = htmlspecialchars ($file);

Now we are finally ready to output the result. I like using HEREDOC when mixing variables with HTML:

echo <<<_
  <li class=files><a href="$href_h" class=filelink>$file_h</a></li>

_;

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