I have a script that retrieves a file through a getfile.php?file=filename.ext. Everything is working fine except when a user clicks 'Open' to a PDF file. It works fine if they save the file, then open it - and also any other file - for example MS Word opens fine.
Here is the code, any reason to be going wrong will be very helpful.
The URL being called is getfile.php?file=Inv00000030.pdf
<?php
session_start();
include("includes/functionlib.inc.php");
dbconnect();
$filename = rawurldecode($_GET['file']);
//Update client log
UpdateLog("Get ".$filename);
//Set file directory
$dir = 'files/'.$_SESSION['username']."/";
$nameparts = explode('.', $filename);
$parts = count($nameparts);
//File extension to determine mime type
$extension = $nameparts[$parts - 1];
//Mime types
$mimetype['pdf'] = "application/pdf";
$mimetype['doc'] = "application/msword";
$mimetype['xls'] = "application/vnd.ms-excel";
$mimetype['jpg'] = "image/jpeg";
$mimetype['png'] = "image/png";
$mimetype['gif'] = "image/gif";
$mimetype['bmp'] = "image/bmp";
if (!isset($mimetype[$extension])) {
$content = "application/octet-stream";
} else {
$content = $mimetype[$extension];
}
$filepath = $dir.$filename;
if (file_exists($filepath) && isset($_SESSION['username'])) {
header('Content-type: '.$content);
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($dir.$filename);
} else {
header("location: index.php?filenotfound=true&file=".rawurlencode($filename));
UpdateLog('File not found '.$filename);
}
?>