I'm looking to pass an arbitrary array from PHP to JavaScript while properly escaping. I'm leaning on using base64 and I imagine that base64 isn't data attribute safe, so as a good developer I am esc_attr the data. Is there a right
way to make sure that the base64 data maintains its integrity in JavaScript?
Here's a contrived example -- that works fine -- because the esc_attr does not modify the integrity of the base64 encoding.
<?php
$array = [
[
'the' => 'quick',
'brown' => 'fox'
],
[
'test' => 'test',
'foo' => 'bar'
]
];
$values_json = base64_encode( json_encode( $array ) );
?>
<input id="check" type="checkbox" data-value="<?php esc_attr_e( $values_json ); ?>"> Foobar
<script>
var checkbox = document.getElementById(id);
checkbox.addEventListener('click',
function () {
console.log(JSON.parse(atob(this.dataset.value)));
}
);
</script>
In my research I came across this solution for handling this using JSON - however the way I am getting the data I don't have an easy way to key the data to retrieve it by using the key as a data attribute.
I'm looking to pass an arbitrary array from PHP to JavaScript while properly escaping. I'm leaning on using base64 and I imagine that base64 isn't data attribute safe, so as a good developer I am esc_attr the data. Is there a right
way to make sure that the base64 data maintains its integrity in JavaScript?
Here's a contrived example -- that works fine -- because the esc_attr does not modify the integrity of the base64 encoding.
<?php
$array = [
[
'the' => 'quick',
'brown' => 'fox'
],
[
'test' => 'test',
'foo' => 'bar'
]
];
$values_json = base64_encode( json_encode( $array ) );
?>
<input id="check" type="checkbox" data-value="<?php esc_attr_e( $values_json ); ?>"> Foobar
<script>
var checkbox = document.getElementById(id);
checkbox.addEventListener('click',
function () {
console.log(JSON.parse(atob(this.dataset.value)));
}
);
</script>
In my research I came across this solution for handling this using JSON - however the way I am getting the data I don't have an easy way to key the data to retrieve it by using the key as a data attribute.
Share Improve this question asked Jun 10, 2017 at 2:55 setterGettersetterGetter 6222 gold badges9 silver badges24 bronze badges1 Answer
Reset to default 1The possible output of base64_encode()
contains a-zA-Z0-9+/
and possibly =
or ==
appended.
Testing with
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';
we find that:
esc_attr( $str ) === $str
is true, so it looks like esc_attr()
preserves base64 encoded strings.
There are possible regexes to help with validation, but according to this answer by @BoltClock, we could check it with the second strict parameter of:
base64_decode( $str, $strict = true )
We could then wrap it in a function like:
function is_base64( $str )
{
return base64_decode( $str, true) !== false;
}
to validate it in PHP.