Cause browser to prompt user to save file you will create from a string

HTML
  <form action="/download-my-file" target="_blank" method="POST">

    <select name="MyDownloadFileId" style="width: 500px;" onchange="this.form.submit()" >
      <option value="0">Select...</option>
      <option value="1">My file 1</option>
      <option value="2">My file 2</option>
    </select>

  </form>
PHP

Basic example:

          header('Content-Disposition: attachment; filename="' . $FileName . '"');
          header('Content-Type: text/txt');
          header('Content-Length: ' . $ContentLength);
          header('Connection: close');

          echo ($FileContent);
          die();

An example using WordPress:

add_action( 'wp', 'mysite_wp' );
function mysite_wp()
{

  if (strpos($_SERVER["REQUEST_URI"], '/download-my-file') !== false)
  {
    if (isset($_REQUEST['MyDownloadFileId']))
    {
      //---------------------------
      //----- DOWNLOAD A FILE -----
      //---------------------------
      if (!current_user_can('administrator'))
        die();
      
      $FileId = intval($_REQUEST['MyDownloadFileId']);
      if ($FileId != 0)
      {
        $Result = db_files_read_file_content($FileId);
        if ($Result !== False)
        {
          $FileName = $Result['FileName'];
          $FileContent = $Result['FileContent'];
          
          $ContentLength = strlen($FileContent);
          
          header('Content-Disposition: attachment; filename="' . $FileName . '"');
          header('Content-Type: text/txt');
          header('Content-Length: ' . $ContentLength);
          header('Connection: close');

          echo ($FileContent);
          die();
        }
      }
    }
  }

}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *