I have a folder in my root dir called files.
This folder contains files ranging from 1 Kb-1 GB.
I want a php script that can simply download a file asynchronously using AJAX.
This codes initiates download scripts when a file is clicked:
JQUERY
$('.download').click(function(){
var src =$(this).attr('src');
$.post('download.php',{
src : src //contains name of file
},function(data){
alert('Downloaded!');
});
});
PHP
<?php
$path = 'files/'.$_POST['src'];
//here the download script must go!
?>
Which would be the best, fastest and secure way to download a file?
<?php
/**
* download.php
*/
if (!empty($_GET['file'])) {
// Security, down allow to pass ANY PATH in your server
$fileName = basename($_GET['file']);
} else {
return;
}
$filePath = '???/files/' . $fileName;
if (!file_exists($filePath)) {
return;
}
header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: application/pdf");
readfile($filePath);
And actually AJAX request is unnecessary, when using Content-disposition: attachment:
File1
To continue on the original answer, I've added a few php functions to make it a bit more programmatic:
$filePath = $_GET['path'];
$fileName = basename($filePath);
if (empty($filePath)) {
echo "'path' cannot be empty";
exit;
}
if (!file_exists($filePath)) {
echo "'$filePath' does not exist";
exit;
}
header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: " . mime_content_type($filePath));
readfile($filePath);
If your sever requires strong security, do not use this function without pre-validating the user in the same script. Or use the security measures posted by the original answer. This script will allow any file on your server to be downloaded by a user.
Related
I'm trying to make 2 option names to download a file: Dictionary and Random.
When the user selects the dictionary option it downloads the file constantly with the name 'download' instead of some random word from the dictionary and the random option works fine.
I tried using the load function and printing what it returns and it does print the actual randomly picked word from the dictionary but it doesn't in the download part. I'm guessing its something with the headers but it might not.
That's the load function which loads the dictionary from a file on the server:
function load($file) {
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
return $rand_text;
}
That's the download function which downloads the file:
function download($file, $filename) {
header("Content-Type: application/jpeg");
header("Content-Length: " . filesize($file));
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($file);
exit();
}
That's how I call the functions:
$filename = load("includes/dictionary_words.txt");
download($file, $filename);
Lastly the $file variable:
$file = "main/app.exe";
Instead of downloading the file with a random dictionary name it downloads it with a 'download' name. I didn't get any errors or notices.
I am trying to download files from server and it works fine for pdf files, I am wondering is there a way to download any type of files such as doc, zip,.. etc.
My code:
<?php
$doc = $sqlite->readDoc($documentId);
if ($doc != null) {
header("Content-Type:" . $doc['mime_type']);
header('Content-disposition: attachment; filename="something"');
print $doc['doc'];
} else {
echo 'Error occured while downloading the file';
}
?>
You'll want to identify the file - maybe using this function:
http://php.net/manual/en/function.mime-content-type.php
and then you can create a switch to indicate the content-type and appropriate disposition. There's a decent example here: PHP - send file to user
A simple function that can be used to download any file formate form path.
function DownloadFile($strFilePath)
{
$strContents = file_get_contents(realpath($strFilePath));
if (strpos($strFilePath,"\\") > -1 )
$strFileName = substr($strFilePath,strrpos($strFilePath,"\\")+1);
else
$strFileName = substr($strFilePath,strrpos($strFilePath,"/")+1);
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"${strFileName}\"");
echo $strContents;
}
Usage Example
$file = $_GET['file_id'];
$path = "../uploads/".$file; // change the path to fit your websites document structure
DownloadFile($path);
I am downloading a file from Ftp folder after upload.
Problem is when i open the txt file it show s html page source appending with file content
If i preview image file(jpg or jpeg) it shows image is corrupted
If i open pdf error: Failed to load Pdf document
Please let me know where i am wrong.
Here is my code:
if (isset($_GET['id']) && basename($_GET['id']) == $_GET['id']) {
$filename = $_GET['id'];
} else {
$filename =NULL ;
}
$err = 'Sorry, the file you are requesting is unavailable.';
if (!$filename) {
// if variable $filename is NULL or false display the message
echo $err;
} else {
// define the path to your download folder plus assign the file name
$path = '/home/devestctrl/public_html/wp-content/uploads/'.$filename;
// check that file exists and is readable
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Type: '.$mime);
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit();
} else {
echo $err;
}
} else {
echo $err;
}
}
I checked by using echo of $filename;
It shows the output in the file instead of printing in page.
error displays:
Sorry, the file you are requesting is unavailable.
After error also i can download, but echoed $filename displayed in file.
Insert into table:
echo "<tr><a href='?id=" . $row["FileupName"]. "'>".$row["FileupName"]."</td></tr>";
You cannot output data to a page and download a file at the same time. One request from your browser will let you do one response. This response is normally displayed in the browser as a page, unless you set the download headers, then the browser will ask you to download the response to a file.
So what you'll need to do is have two requests and responses: In the first, you output your page and a link the user needs to click (or JavaScript or a refresh meta tag to do it automatically) to download the file in a second request.
I want to download and save an Azure Storage blob as a file on my local computer using the file name from the Azure Storage. I'm using the steps from here ( tutorial link ) in a file I've called download.php, and I can see the file contents in my browser when I go to download.php. If I then put a link in index.php to download.php, I can right click the link and "save as", and save the file as myfile.doc. I can then open myfile.doc succesfully.
index.php:
echo '<a href="http://myserver/dev/download.php" >Click me</a>';
However...
What I'd like to know is how to get the link to "save as" without the user having to right click. Also, I have the file name (from Azure Storage) -- but I don't know how to get the file to save using that file name. How do I get the file to save to the user's Downloads directory with the file name when the user clicks on the link?
To do this, I change index.php to a form:
echo '<form method="post" action="download.php"><div id="divexport">';
echo '<input type="hidden" name="Export" value="coverLetter">';
echo '<input type="submit" id="Export" value="Cover Letter" />';
echo '</div></form>';
And then added header info to download.php, just before fpassthru
// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blobfile = "myblob.pdf";
$filename = basename($blobfile);
$ext = new SplFileInfo($filename);
$fileext = strtolower($ext->getExtension());
try {
// Get blob.
$blob = $blobRestProxy->getBlob("document", $blobfile);
if($fileext === "pdf") {
header('Content-type: application/pdf');
} else if ($fileext === "doc") {
header('Content-type: application/msword');
} else if ($fileext === "docx") {
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
} else if($fileext === "txt") {
header('Content-type: plain/text');
}
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
fpassthru($blob->getContentStream());
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP list all files in directory
ive got a cron job running creating .xls files every 24hrs, they are creating them in a directory on my site called www.mysite.com/sheets
what i want to do is make a webpage where i can go to and see all the .xls files in that directory and download the ones i was instead of having to download them using an ftp client.
Is there a name for this sort of thing ? what would i write it in ? i was thinking i could do it in php by echoing the folders contents, would that work ?
cheers
You could activate directory listing within your webserver, or you can use a function like glob("*.xls") to list the files and echo their path on the webserver or you can send a file to the browser like this:
<?php
$filename = "path/to/your/file.xls";
$real_filename = "file.xls";
header('Content-Transfer-Encoding: none');
header('Content-Type: application/octet-stream; name="' . $real_filename . '"');
header('Content-Disposition: attachment; filename=' . $real_filename);
$size = #filesize($filename);
if ($size > 0) {
header('Content-length: '.$size);
} else {
header('Content-length: '.#strlen(#file_get_contents($filename)));
}
readfile($filename);
exit;
?>
If you want to list a directory use this:
$handle = opendir("./");
while (false !== ($file = readdir($handle))) {
$fileinfo = pathinfo($file);
if (strtolower($fileinfo[extension]) == "xls") {
echo $file;
}
}
closedir($handle);
Or this:
foreach (glob("*.[xX][lL][sS]") as $filename) {
echo $filename;
}
Use glob() plus some filtering for xls files.
glob("*.xls")
Potentially useful resources (in order of preference):
Manual
http://php.net/filesystemiterator
http://php.net/glob
http://php.net/scandir
http://php.net/opendir
http://php.net/function.dir