title: AngularJS stream audio from PHP server 2
body: <p>I have the following PHP code which authenticate to a third-party server using JWT and download the recorded audio from the server and then it serves the .mp3 to javascript which constructs an Audio object to playback the audio. How to do this more efficiently?</p>
  
  <pre><code>use Lcobucci\JWT\Builder;
  use Lcobucci\JWT\Signer\Key;
  use Lcobucci\JWT\Signer\Rsa\Sha256;
  private function generate_jwt() {
      $dev = preg_match("/blah.blah.com/", $_SERVER["HTTP_HOST"]);
      $jwt = false;
      date_default_timezone_set('UTC');    //Set the time for UTC + 0
      //$key = file_get_contents($keyfile);  //Retrieve your private key
      $key = $dev ? self::DEV_KEY : self::PRODUCTION_KEY;
      $id = $dev ? self::DEV_ID : self::PRODUCTION_ID;
      $signer = new Sha256();
      $privateKey = new Key($key);
      $jwt = (new Builder())-&gt;setIssuedAt(time() - date('Z')) // Time token was generated in UTC+0
          -&gt;set('application_id', $id) // ID for the application you are working with
          -&gt;setId( base64_encode( mt_rand (  )), true)
          -&gt;sign($signer,  $privateKey) // Create a signature using your private key
          -&gt;getToken(); // Retrieves the JWT
      return $jwt;
  }
  public function playback($url) {
      $response = "";
      if (!empty($url)) {
          //Create your JWT
          $jwt = $this-&gt;generate_jwt();
          //Add the JWT to your headers
          $headers =  array('Content-Type: application/json', "Authorization: Bearer " . $jwt);
          $ch = curl_init();
          //Make a request to $recording_url
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
          $file = __TMPDIR__ . basename($url).".mp3";
          file_put_contents($file, $response);
          header('Pragma: public');   // required
          header('Content-Type: audio/mpeg');
          header('Content-length: ' . filesize($file));
          header("Content-Transfer-Encoding: binary");
          header('Content-Disposition: filename="' . basename($file));
          header('X-Pad: avoid browser bug');
          header('Cache-Control: no-cache');
          $len = readfile($file);
      } else
          error_log(__FILE__." ".__FUNCTION__." ".__LINE__.": Invalid url! ".$url);
  }
  </code></pre>