Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
How can I set JavaScript variables from PHP script while adhering to Content Security Policy

We are re-architecting some of our applications, and one of the requirements is to be able to adhere to content security policies that disallows inline scripts.

In general most of the event handlers and blocks of logic are already in external files, and moving the remaining stragglers isn't an issue, with the following exception.

We have settings that are stored in a SQL database, and we must make some of these values available to the .js files for the rendered HTML page.

Normally I'd do something like:

<script>
var ns.i = '<?= $i;?>',
    ns.j = '<?= $j;?>';
</script> 

Seems to me I have these potential options:

  1. Put the required values in an associative array, json_encode it, put it in a hidden form field. This feels like a hack to me, but also the simplest from my perspective.
  2. Create a div tag and put all the values in HTML 5 data attributes.
  3. Create a form and put the values into hidden form fields.
  4. Generate a nonce and set the nonce attribute on the script tag, and set the CSP header nonce.

I have thus far been unable to locate recommendations or documented best practices for this type of thing.

refactoring this code is a lot of work and I want to do my best to ensure we're doing it the best way possible at this time.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!