Php download file of any extension from server

I am looking for just one php script to download files of any extension in particular doc, docx, pdf, jpg, png, gif.
Either the file will open in a browser or a dialog comes on to save the file
I searched through the internet and got different solution for different extension. Here are 3 examples:

    // This is only good only for pdf 
	$file = 'path/testfile.pdf';
	if (file_exists($file)) {
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename="'.basename($file).'"');
		header('Expires: 0');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		header('Content-Length: ' . filesize($file));
		readfile($file);
		exit;
	}

//ok only for pdf, docx by changing header Content-type:application
	$file = 'testfile.docx';
	$filename = 'path/testfile.docx';	
	header("Content-type:application/docx");
	header("Content-Disposition:attachment;filename=".$file."");
	readfile($filename);

// saves image file but microsoft office apps, pdf app, etc. cannot open file 
$file = 'path/testfile.jpg';
	$filename = 'testfile.jpg';
	header('Content-type: application/jpg');
	header('Content-Disposition: inline; filename="'.$filename.'"');
	header('Content-Transfer-Encoding: binary');
	header('Accept-Ranges: bytes');
	@readfile($file);

I need just one script to satisfy all types of files

create a dictionary of file types. Then when a file is requested, look up the content-type and use the specific type for that document.

Thanks. I am trying to avoid this hoping just one script will satisfy all types of files. I will go along your route.

It’s still one script, it’s just dynamic to cover possibilities. Everything else stays the same.

This will allow downloads of any filetype. Just include the filetype in the filename.
( Note: This will NOT force the browser to open in the correct application! )

Thanks for all your useful inputs.
I finally used the scirpt below and it works fine for any file format.

$ul = '<ul>';
$dir = ../myfolder/;
$arr = @scandir($dir);
$arr_le = @count($arr);
for ($p=0; $p<$arr_le; $p++) {
  if ($arr[$p] != '.' && $arr[$p] != '..') {
    $path = $dir.$arr[$p];    
    $ul .= '<li><a href="'.$path.'" target="_blank">'.$arr[$p].'</a></li>';
  }
}
$ul .= '</ul>';

$ul is added to the html.
A click on any of the links on the web page will open the file (I noticed this for pdf, jpg, png, gif) and if it cannot, a save dialog box will come up (I noticed this for doc, docx)

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service