download a file

function sendFileToBrowser() {
/*
This function uses the technique from the book which showed me how to send
a file to the browser in such a way that it will become a download.
*/
  $docRoot = $_SERVER["DOCUMENT_ROOT"];
  $scriptFileDir = $_SESSION['CPSAK_scriptFileDir'];
  $scriptFileName = $_SESSION['CPSAK_scriptFileName'];
  $locatorStr = $docRoot . $scriptFileDir . $scriptFileName;

  if (isset($_POST['submitToken'])) {
    $submitToken = $_POST['submitToken'];
  } else {
    $submitToken = "";
  }
  if ($submitToken != $_SESSION['CPSAK_submitToken']) {
    form_destroy();
    $host = $_SERVER['HTTP_HOST'];
    $uri = $_SERVER['PHP_SELF'];
    header("Location: http://$host$uri");
    exit;
  }

  $fp = fopen($locatorStr, "r");
  header("Content-Type:text/plain;charset=utf-8");
  header("Content-Disposition:attachment;filename=$scriptFileName");
  header("Content-Transfer-Encoding:binary");
  fpassthru($fp);
  fclose($fp);

  return;
}
Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in Coding, PHP and Filesystem and tagged , , . Bookmark the permalink.

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s