Escaping special characters in javascript in a link - javascript

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>
_;

Related

JSON.parse string with single and double quotes?

I am saving an array as json and parsing it again upon load. However, after adding HTML with both single and double quotes, this has stopped working.
How can I escape the quotes?
JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]');
uncaught SyntaxError: missing ) after argument list
EDIT:
My string is saved in database using JSON.stringify. It ends up in the following format:
[["ad",null,true,false,true,false,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]
when Im loading it again, I do it like follows:
var phpsave = JSON.parse('<?php echo $result->save; ?>');
If im escaping the single quotes before saving, the escaping just dissappears upon loading..
You're dynamically producing Javascript source code. You need to ensure that what you're producing is syntactically valid. The easiest way to produce valid Javascript literals from PHP is using json_encode:
var phpsave = JSON.parse(<?php echo json_encode($result->save); ?>);
// look ma, no quotes! ^ ^
But wait, aren't you passing JSON to your Javascript? Isn't JSON already valid Javascript? Why, yes, yes it is. So you can leave out that step:
var phpsave = <?php echo $result->save; ?>;
Of course, you might want to ensure that you're really passing valid JSON here first before you start outputting random Javascript code.
You can escape it like
var r = JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class=\'fa fa- plus - circle fa- lg\'></i></span>"]]');

Escaping characters in JavaScript or PHP [duplicate]

I'm looking for the best way to escape some Javascript text in PHP, and json_encode is the wrong tool for the job.
The problem comes from this line:
echo " onclick=\"SwitchDiv('" . $option . "')\"";
If there's an apostrophe in $option, this is a juicy ball of client-side fail. But doing a straight json_encode (which works perfectly well in other contexts) doesn't help:
echo " onclick=\"SwitchDiv(" . json_encode($option) . ")\"";
That creates an output string of onclick="SwitchDiv("athlete's foot")", resulting in premature termination of the onclick value. (Which also happens if I enclose the onclick value in single quotes.)
Is there an elegant way around this? Should I just funnel the json_encode output through a regex that will escape the single quotes?
json_encode is the right tool for the job. Your problem arises from the fact that you are also including that Javascript in an HTML attribute, thus it also needs to be htmlspecialchars-encoded.
echo " onclick=\"SwitchDiv(" . htmlspecialchars(json_encode($option)) . ")\"";

php echo outputting html as text

I am trying to use php to construct html code containing onclick="Javascript" within
i keep getting an error saying that i am missing a } within the console, however this is not the case.
despite the error the site displays perfectly
I then followed this post
How should I echo a PHP string variable that contains special characters?
and used the method htmlentities
at first it appeared to work correctly however i must have changed something because now it outputs the html string as text and not displaying the element
this issue is present across different platforms/browsers, so i dont believe that it is cache related problem.
there are other elements within the php script that output the html correctly, it just appears that its this line.
Thanks in advance
echo htmlentities('<h2 class="page_title">' . $db_field['Title'] . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
You should not use htmlentities() on strings that you actually want to be interpreted as HTML, since it will convert the < and > into entities so they display literally. Just call it on the variables that you don't want interpreted:
echo '<h2 class="page_title">' . htmlentities($db_field['Title']) . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
Why such violence?
here is how to output templates using PHP :
<?php
//blablabla my php stuff here...
?>
<h2 class="page_title">
<?=htmlentities($db_field['Title'])?>
</h2>
<a onclick="showAndroidToast('<?=$_SESSION[\'user_id\']?>','<?=$db_field[\'ID\']?>');
<img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px">
</a>
Whenever you call htmlentities(), whatever in it will be translated into characters that the browser interprets as literal symbols to show. This is how we can tell browsers to display HTML and code without actually interpreting it. It also allows us to show symbols we don't want the browser to accidentally parse. If you have a string containing HTML that you want to be interpreted by the browser, DO NOT use htmlentities().
You don't want:
print htmlentities("<h1>I have a < and > sign I don't want interpreted</h1>");
You actually do want:
print '<h1>' . htmlentities("I have a < and > sign I don't want interpreted") . '</h1>';
Read the docs: http://php.net/manual/en/function.htmlentities.php

What is a proper way to escape HTML for Javascript function?

I'm getting Uncaught SyntaxError: Unexpected identifier
due of the Java-Script clashing syntax or single and double quote.
In the source file,the $str is escaped as special chars but not sure why Javascript will hit error.
What is the Correct/Proper way to escape it with single or double quote inside a string for Javascript function use purpose?
Below is my code :
<?php
$str = 'I\'m John Doe < lol > "19" ! ?';
?>
<div onclick="alert('<?php echo htmlspecialchars($str); ?>')">Test</div>
<div onclick="alert("<?php echo htmlspecialchars($str); ?>")">Test</div>
The important thing to note here is that you don't just have JavaScript. You have JavaScript in an HTML attribute, so you have to escape for JS then for HTML.
json_encode will escape for JS. It will also add quotes around strings, so do you don't need to do that yourself.
htmlspecialchars will escape for HTML.
onclick="alert(<?php echo htmlspecialchars( json_encode( $str ) ); ?>"
Any time you're using strings in the context of JavaScript, use JSON-encoding. JSON is compatible with JavaScript parsers, and all of the escaping needed will be done for you.
var str = <?php json_encode($str) ?>;

PHP change href on specific pages

I am new to PHP. I am trying to replace the hash tags in the headers of all the pages that aren't part of the index page. I am using this code
$content = file_get_contents('includes/header.php');
if ( strpos( $_SERVER['SCRIPT_NAME'], 'index.php' ) === false ){
preg_replace( 'href="#', 'href="index\.php#', $content );
}
However I am getting "Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in " and I don't know how to escape the characters more than using backslash.
Should I just run some javascript instead?
Thanks
preg_replace expects parameter 1 to be a pattern and is missing the delimiters. So you need to do something like:
preg_replace('/href="#/', 'href="index\.php#', $content);
http://www.php.net/preg_replace
The 'hash' of the url cannot be accessed by the server, only by the client.
The only way to manipulate this part of the URL is by using a client side scripting language, e.g. JavaScript.

Categories