title: Subresource integrity and cache busting techniques in PHP
body: <p>I'd like to implement <a href="https://www.w3.org/TR/SRI/" rel="nofollow"><strong>Subresource Integrity</strong></a> and <strong>cache busting</strong> for static assets such as stylesheets and JavaScript files in my application. Currently I use PHP with Twig templates.</p>
  
  <p>I know there are many tools out there to generate hashes for all the JS and CSS files but I am looking for how to implement the hashes into the <code>&lt;script&gt;</code> and <code>&lt;link&gt;</code> tags for hundreds of files.</p>
  
  <p><a href="https://adactio.com/journal/8504" rel="nofollow">This blog post</a> described most of what I'm trying to do, however the author only covers cache busting and uses a static timestamp in the file name that he changes manually every time. Using a build tool to programatically generate that timestamp isn't difficult either but with SRI the value is a hash, which is <em>different for every file</em>.</p>
  
  <p>For example, a snippet of <code>header.html.twig</code>:</p>
  
  <pre><code>&lt;!-- cdn requests --&gt;
  
  &lt;script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'
      integrity='sha384-8gBf6Y4YYq7Jx97PIqmTwLPin4hxIzQw5aDmUg/DDhul9fFpbbLcLh3nTIIDJKhx'
      crossorigin='anonymous'&gt;&lt;/script&gt;
  
  &lt;!-- same-origin requests --&gt;
  
  &lt;script src='foo.1a516fba.min.js' 
      integrity='sha384-GlFvui4Sp4wfY6+P13kcTmnzUjsV78g61ejffDbQ1QMyqL3lVzFZhGqawasU4Vg+'&gt;&lt;/script&gt;
  &lt;script src='bar.faf315f3.min.js'
      integrity='sha384-+vMV8w6Qc43sECfhc+5+vUA7Sg4NtwVr1J8+LNNROMdHS5tXrqGWSSebmORC6O86'&gt;&lt;/script&gt;
  </code></pre>
  
  <p>Changing the <code>src</code>/<code>href</code> and <code>integrity</code> attributes every time is not a sane approach.</p>
  
  <p>I could write a Twig function that calls a PHP function to hash the file every time and it may work on OK on dev but that seems awfully computationally expensive.</p>
  
  <p>What is a feasible approach to this?</p>