Download Files from Server PHP

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");

// read the file from disk
readfile($file);
}

PHP - Download file(s) from the server without revealing the URL - A few GOTCHAS

To get this working in my own code, I needed to wrap my PHP variables in either single or double quotes (and sometimes doubled single quotes) as shown below:

header('Content-Type:'.$ctype.'' ); 
header('Content-Disposition: attachment; filename="'.$fname.'"');
readfile(''.$filepath.'');

When entered this way, I was able to download the files without corruption or issue. Please let me know if you are aware of a better way of doing this.

However, when I used the coded above it also allowed me to NOT use the

            ob_clean();
ob_end_flush();

commands in my code. In fact if I add them now . . . it seems to corrupt my files too. Weird.

Another potential GOTCHA is that if you attempt to download a TXT file, and you have a PHP "echo" statement anywhere in your "download.php" file, the contents of the ECHO statement will be appended to the TXTY file that's downloaded. So just something to be careful of.

This ECHO statement may also be appended to the headers of other documents types as well, but it didn't seem to affect the ability of the file to open in my limited testing. But again, be careful out there! :)

Download file from server to clients system via php

I may be a little off my rocker here, but there is a much simpler way ( I think! ) to simply download a file.

$file = "/home/demo/public_html/testwordpress/csv/sale.csv";
$contents = file_get_contents($file);

// Manipulate the contents however you wish.
$newFilePath = "somewhere/over/the/rainbow/sale.csv";
file_put_contents($newFilePath, $contents);
  • The file_get_contents will work with http streams as well.

Download File to server from URL

Since PHP 5.1.0, file_put_contents() supports writing piece-by-piece by passing a stream-handle as the $data parameter:

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));

From the manual:

If data [that is the second argument] is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using
stream_copy_to_stream().

(Thanks Hakre.)

Download file from Server PHP

To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type):

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));

// Then:

flush(); // just in case
readfile($filename);

To output an image in the browser, try:

header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);

// Then:

$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);

To different methods of outputting the file size are given.

PHP script for downloading files through website from a list page containing files in specified folder on server

The code that

  1. Lists the files
  2. Downloads a file

must be separate.


(While not strictly necessary), easy way is to put them into separate files, like list.php and download.php. The list.php will generate a list of download links, which will points to download.php (what you already do in the opendir ... closedir block):

if ($handle = opendir('uploads/')) {
while (false !== ($entry = readdir($handle)))
{
//
if ($entry != "." && $entry != "..") {
//download.php is the file where we write the code
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}

closedir($handle);//
}

The download.php will contain the rest of your code:

// we are trying to get the files by listing it with .$file variable
$file = basename($_GET['file']);
$filepath = 'uploads/'.$file;

if(!file_exists($filepath)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public"); //
header("Content-Description: File Transfer");//
header("Content-Disposition: attachment; filename=$file");//
header("Content-Type: application/zip");//
header("Content-Transfer-Encoding: binary");//

// read the file from disk
readfile($filepath);
}

(I have replaced your strange mimi_exists with file_exists and fixed the issues that internal "upload" file path got accidentally sent to the browser)


A similar question: List and download clicked file from FTP.

How to download a file from server, using PHP Code

You can use Curl to download file from web using php

function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}

pass url to this function and download contents. alternatively you can use file reader/writer

private function downloadFile ($url, $path) {
$newfname = $path;
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}

from : This stack question



Related Topics



Leave a reply



Submit