Whats wrong with my code for downloading files in php? - php

download.php:
<?php require_once('Connections/connection_psfriend.php'); ?>
<?php
$idreceived = addslashes($_REQUEST['sendid']);
$filepathquery = "SELECT bd_brushfilepath FROM tbl_brushdescription WHERE bd_brushid = $idreceived";
$Recordset = mysql_query($filepathquery,$connection_psfriend) or die(mysql_error());
$filepath = mysql_fetch_assoc($Recordset);
$receivedfilerequest = $filepath['bd_brushfilepath'];
$file_path = $_SERVER['DOCUMENT_ROOT'].'/'.'ps-friend'.'/' . $receivedfilerequest;
$updatedownlaodquery = "UPDATE tbl_brushdescription SET bd_brushdownloads = bd_brushdownloads + 1 WHERE bd_brushid = $idreceived";
$Recordset = mysql_query($updatedownlaodquery,$connection_psfriend) or die(mysql_error());
if(file_exists( $file_path)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file_path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
ob_clean();
flush();
readfile($file_path);
exit;
}
My problem:
The code works fine with google Chrome for all 143 entries made in the database. It works fine fine with Firefox too except for 5 out of those 143.
for firefox it shows:( for those 5 entries):
In the database, I am using filepaths to store the files. All the files are either in zip format or rar format. Those files are not downloaded in rar/zip format. With google chrome, there is no problem at all. Is there something wrong with the script?

First of all, please stop using MYSQL_ function, see why-shouldnt-i-use-mysql-functions-in-php.
Secondly you are using $idreceived = addslashes($_REQUEST['sendid']); as a nice way to prevent SQL injection. Unfortunately you are calling the query like WHERE bd_brushid = $idreceived, so without quotes.
In other words, you are still vulnerable, as long as I dont use any quotes. Consider me sending sendid=1 OR 1=1. All your rows would be updated in the second query.
Change it to WHERE bd_brushid = '$idreceived', or even better: check how-to-prevent-sql-injection-in-php
Now to your problem. I think you should change one line to the following to include quotes
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
If it still does not work, send the right content type in the header.
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $file_path);
header('Content-Type: '.$type)
?>

The following has always worked for me
$file=$_POST['file'];
header( "Content-Disposition: attachment; filename=$file" );
readfile("$_POST[file]");
without any of the content type headers.However my file extension is .zip.Your file does not seem to have an extension.

Related

Convertig excel base64 to downloadable file PHP

everybody, im running in some issue right now, see for internal situations with the server that i cant control or anything right now i cant use base64 encoded files directly over the website cause when the server delivers content to the browser it has a limit of characters for those tasks and it directly affects base64 encoded files cause of the lenght of those strings, so i made for one system a php script that delivers an already existing base64 pdf files to the client as a downloadable file, and it worked just like this:
$reg = File::find($args->string('id')); //querying the file from database
$filename = $reg->filename; //the original file name
$base64 = $reg->file; //the base64 encoded file
$meta_type = explode(',', $base64) [0]; //getting the meta type of the file
$meta_type = str_replace('data:', '', $meta_type);
$meta_type = str_replace(';base64', '', $meta_type);
$file = explode(',', $base64) [1];
$file = base64_decode($base64); //decoding the base64 string
header('Content-Description: File Transfer');
header('Content-Type: ' . $meta_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . (strlen($file)));
echo $file;
this worked just fine when i use pdf files but when i try to use it on some 'xlsx' files it seem to work, it download the file, the filesize and all seem to match the original, but excel cant open the file, does anybody have an idea of what im i missing here?? :)
I am pretty sure, its happening, because you are not exiting your function and it continues to fill up buffers. You have to stop the script immediatelly after your stream is ready, clean the buffer and exit.
If its a valid Excel file, all you have to do is:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: must-revalidate');
header('Expires: 0');
header('Pragma: public');
header('Content-Disposition: attachment; filename="' . $filename . '"');
if (ob_get_contents() || ob_get_length()) {
ob_end_clean(); //or ob_end_flush();
}
exit();

Trouble forcing ZIP download from PHP web app

This php file is supposed to:
receive a piece of information from a form on a different page
use this information to create an array of file paths to add to a zip file
create a dynamically named zip file using a class that's included.
force the download of the newly created zip file
numbers 1-3 are working flawlessly.
The page even forces the download of a zip file that is correctly named and is the right size, but when I try to open it, it says the file is invalid. I've seen similar problems in searches, but I have yet to find a solution.
If i enter the direct URL for the newly created zip into the browser, the file downloads and opens perfectly. As a matter of fact, my temporary fix was creating a dynamic direct link to the files :/
I should probably mention that this is hosted on the go daddy economy plan.
<?php
error_reporting(0);
include "gavScripts/connect_to_mysql.php";
require_once 'Zipper.php';
// prepare the file paths to add to the zip file and find the job/client name (for naming the zip folder)
if(isset($_POST['jobName']))
{
$clientID = $_POST['jobName'];
$clientSQL = mysql_query("SELECT clientName FROM job_client WHERE clientID = $clientID");
while($clientRow = mysql_fetch_array($clientSQL))
{
$clientName = $clientRow['clientName'];
}
$zipSQL = mysql_query("SELECT filePath FROM job_expense WHERE clientID = $clientID");
While($zipRow = mysql_fetch_array($zipSQL))
{
$filePaths[] = $zipRow['filePath'];
}
}
//create the zip folder and store the requested files
$zipper = new Zipper();
$zipper->add($filePaths);
$zipper->store('invoices/' . $clientName . '_Invoices.zip');
//download the zip
$fileDownload = 'invoices/' . $clientName . '_Invoices.zip';
$fileName = basename($fileDownload);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . $fileName . "");
header("Content-Length: " . filesize($fileDownload));
readfile($fileDownload);
?>
You may have trailing whitespace at the end of your script which is breaking your zip file. Is there a \r or \n (or both) after the closing ?>? Try removing the closing ?> which is optional anyway.
Try the following:
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime($fileName)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileName));
header('Connection: close');
readfile($fileName);
exit();
Might help.

View file stored in database using php on browser

I'm trying to view files (i.e: excel sheets/pdf/images) on browser that are stored in database.
I already wrote a code for downloading the files from the database and it is working but I want to display it in the browser.
Here is the code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
$id = $_GET['id']; // ID of entry you wish to view. To use this enter "view.php?id=x" where x is the entry you wish to view.
$query = "SELECT fileContent, filetype FROM file where id = $id"; //Find the file, pull the filecontents and the filetype
$result = MYSQL_QUERY($query); // run the query
if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one)
{
$data = $row[0]; // First bit is the data
$type = $row[1]; // second is the filename
Header( "Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :)
print $data; // Send the data.
}
else // the id was invalid
{
echo "invalid id";
}
?>
What happens is that view.php is downloaded and nothing is viewed.
Any suggestions?
According to your code, $row[1] is "the filename". The Content type header should contain the content type instead, i.e. the file mime type, for example:
header('Content-type: application/pdf');
If you want to add a filename:
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename='.$row[1]);
print $data;
Be sure $data is the content of the file, something you can take from readfile() for example.
Read more on the manual: http://php.net/manual/en/function.readfile.php
Keep in mind that while PDF and images are easily viewable by a browser, I think Excel needs some ad hoc plugin for that.
A more complete example right out of the manual, to get you a more thorough idea (not all those headers are necessary, and you should change others accordingly to your code):
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

File download from server using mysql and PHP

I have created a PHP page that allows users to download a file when they click the this link:
Download File
I have also created the download page that the link directs to:
<?php
if(isset($_GET['file'])) {
$fileID = $_GET['pubid'];
$filename= ($_GET['file']);
$path = "admin/pubfiles/";
$fullPath = $path . $filename;
mysql_select_db($database_connDioceseofife, $connDioceseofife);
$sql = "SELECT file FROM publications WHERE pubID = $fileID";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if($filename == NULL) {
die('No file exists or the name is invalid!');
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($fullPath);
}
?>
Now my problem is, when the download popup window come up, it reads that the file is of 0 bytes. And when downloaded, it can't open. i get the message that it is not a supported file type or its been damaged or corrupted.
Please any help would be much appreciated.
You're not doing anything with the query result in $row.
Use $row['file'] to get the actual file itself.
Thank you all for assisting me. I have been able to solve the problem after further reading. I have updated the initial script i wrote. what is above is now the working script.
What i did was to include $fullpath = $path . $filename then changed the header("Content-Disposition: attachment; filename=\"$filename\""); and then the readfile function from readfile($path) to readfile($fullpath).
Thanks again #nlsbshtr and everybody else for your help.

Cannot download pdf using ipad

I am using the following function to download pdf file it is working fine when i download it from PC or laptop but when i click on download link using ipad it opens a page with lots of special chracters and I am unable to download the file.
My download function is
public function download() {
$download_path = $_SERVER['DOCUMENT_ROOT'] . "/import";
$filename = $_GET['file'];
$file = str_replace("..", "", $filename);
$file = "$download_path/$file";
if (!file_exists($file))
die("Sorry, the file doesn't seem to exist.");
$type = filetype($file);
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header('Pragma: no-cache');
header('Expires: 0');
readfile($file);
}
Any idea about this error ?
This is probably the issue:
$type = filetype($file);
header("Content-type: $type");
From the manual
Possible values are fifo, char, dir, block, link, file, socket and
unknown.
Which are not things you want to see in the header. You are probably looking for:
header('Content-type: application/pdf');
You probably want finfo_file() and not filetype().

Categories