I wanted to pass PHP variables to Javascript without triggering any new http request (aka: inserting it directly in markup). But I wanted the content as is (without any sanitization that could change my values, even if they where markup itself). Of course I wanted to keep it safe as well.
The best way i’ve came up so far includes json + base64_encode + data uri schemes:
<script type="text/javascript" src="data:text/javascript;base64,<?php echo base64_encode('var thing = '.json_encode($thing)); ?>"></script>
My question is: will this have any side effect? can I safely use this?
I certainly wouldn’t do this. You’re introducing unnecessary compatibility problems (IE). By base64 encoding, you’re bloating the size of your JSON by ~37%.
Realistically, the only problem you might run in to is if(It looks like$thinghas a ‘</script>‘ in a string somewhere.json_encode()actually escapes all forward slashes/, so this isn’t a problem.) HTML parsers will ignore anything else that might look like markup in a<script>block.You do have to watch out for text encoding if your page isn’t UTF-8.