I am creating a dynamic regex but I have a problem with how to escape character so can one put some light on this?
I am using PHP with some backend configuration and admin can add regexp from backend to validate invalidate character and I am getting this value on the PHP so what I did
var regex = RegExp(<?php echo $regex ?>);
but I am getting the error like SyntaxError: Invalid regular expression: I know I need to escape the dynamic character but not sure how.
EDIT
I am trying this value from backend
<>{}[\]!##$+=%^*()/;
New EDIT
As per the #anubhava suggested I am escaping the special character by preg_quote() but on Regex.test it always fails I mean it always getting the false even though It should return true.
Here is my code,
var invalidCharRe = new RegExp(SOME_MY_VARIABLE);
var result = invalidCharRe.test(value)
Where SOME_MY_VARIABLE is a dynamic special character(which I am getting from PHP by preg_quote() and value is my textbox value
Since you're using php to echo your regex you can leverage php's preg_quote function to escape all special regex meta-characters beforehand like this:
var regex = /<?php echo preg_quote($regex, '/'); ?>/
Note that there is no need to call new RegExp here since Javascript will be always be getting a static string for regex.
I am encoding JSON with spaces in the string in PHP before passing it to Vue.js, however the process is failing. If I test without the spaces everything is fine.
I am sure there is a basic bit of theory than I am just not aware of but if someone could explain that would great.
The encoding code is below:
<?php $f = Session::get('foods');?>
<?php $a = json_encode($f); ?>
Passing to Vue
<credits f = {{$a}} a = {{$b}} c={{$cr}}></credits>
You need quotes around the attributes if they can have spaces.
<credits f='{{$a}}' a='{{$b}}' c='{{$cr}}'></credits>
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>
_;
I have this row that gives me an error because the value contains HTML Code.
document.getElementById(\'longstory\').value = \''.$row['longstory'].'\';
Is there any easy way to like encode it during passing and then when showing it in my value
<textarea class="form-control" id="longstory" name="longstory" placeholder="Longstory"></textarea><br />
to get it show as HTML for the user in the end?
Try this:
echo "document.getElementById('longstory').value = " . json_encode(html_entity_decode($row['longstory'])) . ";";
html_entity_decode() will interpret HTML entity codes in the value, converting them into normal PHP characters. Then the output of json_encode() will be Javascript syntax for the value.
The problem isn't that it contains HTML, the problem is that it contains characters that aren't permitted in a Javascript string, such as unescaped quotes and literal newlines. json_encode encodes everything properly.
Try use the htmlspecialchars and addslashes functions before passin to the js.
document.getElementById(\'longstory\').value = \''.addslashes($row['longstory']).'\';
I need to put a JSON object into an attribute on an HTML element.
The HTML does not have to validate.
Answered by Quentin: Store the JSON in a data-* attribute, which is valid HTML5.
The JSON object could be any size - i.e. huge
Answered by Maiku Mori: The limit for an HTML attribute is potentially 65536 characters.
What if the JSON contains special characters? e.g. {foo: '<"bar/>'}
Answered by Quentin: Encode the JSON string before putting it into the attribute, as per the usual conventions. For PHP, use the htmlentities() function.
EDIT - Example solution using PHP and jQuery
Writing the JSON into the HTML attribute:
<?php
$data = array(
'1' => 'test',
'foo' => '<"bar/>'
);
$json = json_encode($data);
?>
CLICK ME
Retrieving the JSON using jQuery:
$('a').click(function() {
// Read the contents of the attribute (returns a string)
var data = $(this).data('json');
// Parse the string back into a proper JSON object
var json = $.parseJSON($(this).data('json'));
// Object now available
console.log(json.foo);
});
The HTML does not have to validate.
Why not? Validation is really easy QA that catches lots of mistakes. Use an HTML 5 data-* attribute.
The JSON object could be any size (i.e. huge).
I've not seen any documentation on browser limits to attribute sizes.
If you do run into them, then store the data in a <script>. Define an object and map element ids to property names in that object.
What if the JSON contains special characters? (e.g. {test: '<"myString/>'})
Just follow the normal rules for including untrusted data in attribute values. Use & and " (if you’re wrapping the attribute value in double quotes) or ' (if you’re wrapping the attribute value in single quotes).
Note, however, that that is not JSON (which requires that property names be strings and strings be delimited only with double quotes).
Depending on where you put it,
In a <div> as you asked, you need to ensure that the JSON does not contain HTML specials that could start a tag, HTML comment, embedded doctype, etc. You need to escape at least <, and & in such a way that the original character does not appear in the escaped sequence.
In <script> elements you need to ensure that the JSON does not contain an end tag </script> or escaping text boundary: <!-- or -->.
In event handlers you need to ensure that the JSON preserves its meaning even if it has things that look like HTML entities and does not break attribute boundaries (" or ').
For the first two cases (and for old JSON parsers) you should encode U+2028 and U+2029 since those are newline characters in JavaScript even though they are allowed in strings unencoded in JSON.
For correctness, you need to escape \ and JSON quote characters and it's never a bad idea to always encode NUL.
If the HTML might be served without a content encoding, you should encode + to prevent UTF-7 attacks.
In any case, the following escaping table will work:
NUL -> \u0000
CR -> \n or \u000a
LF -> \r or \u000d
" -> \u0022
& -> \u0026
' -> \u0027
+ -> \u002b
/ -> \/ or \u002f
< -> \u003c
> -> \u003e
\ -> \\ or \u005c
U+2028 -> \u2028
U+2029 -> \u2029
So the JSON string value for the text Hello, <World>! with a newline at the end would be "Hello, \u003cWorld\u003e!\r\n".
Another way you can do it – is put json data inside <script> tag, but not with type="text/javascript", but with type="text/bootstrap" or type="text/json" type, to avoid javascript execution.
Then, in some place of your program, you can ask for it in this way:
function getData(key) {
try {
return JSON.parse($('script[type="text/json"]#' + key).text());
} catch (err) { // if we have not valid json or dont have it
return null;
}
}
On server side, you can do something like this (this example with php and twig):
<script id="my_model" type="text/json">
{{ my_model|json_encode()|raw }}
</script>
Another option is to base64 encode the JSON string and if you need to use it in your javascript decode it with the atob() function.
var data = JSON.parse(atob(base64EncodedJSON));
For simple JSON objects, the code below would work.
Encode:
var jsonObject = { numCells: 5, cellWidth: 1242 };
var attributeString = escape(JSON.stringify(jsonObject));
Decode:
var jsonString = unescape(attributeString);
var jsonObject = JSON.parse(jsonString);
You can use knockoutjs,
<p>First name: <strong data-bind="text: firstName" >todo</strong></p>
<p>Last name: <strong data-bind="text: lastName">todo</strong></p>
knockout.js
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Jayson";
this.lastName = "Monterroso";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
Output
First name: Jayson
Last name: Monterroso
Check this:
http://learn.knockoutjs.com/
Nothing fancy here. From PHP, give the JSON string a run through htmlspecialchars to make sure no special characters can be interpreted as HTML. From Javascript, no escaping necessary; just set the attribute and you're good to go.
Another thought that could be used is store the JSON data as a base64 string in the attribute and then using window.atob or window.btoa to restore it to usable JSON data.
<?php
$json = array("data"=>"Some json data thing");
echo "<div data-json=\"".base64_encode(json_encode($json))."\"></div>";
?>
What you can do is use cdata around your element/s like this
<![CDATA[ <div class='log' mydata='${aL.logData}'>${aL.logMessage}</div> ]]>
where mydata is a raw json string. Hope this helps you and others.
In our case replace ' by ' and inserting the json between simple quotes works perfectly for vue:
php:
$data = json_encode($data);
$data = preg_replace("/'/", ''', $data);
html:
<vue_tag :data='<?=$json?>' />