Download links php - php

I'm trying to make an interface where user can log in and download files from a ftp server. I got a problem with my download links, and it only downloads the last file in the list even if i press the first.
Here is my code:
$a = ftp_nlist($conn_id, "/web/images");
foreach($a as $value){
if ($i <= 1) {
$i ++;
}
else {
echo "<br>";
echo '<ul><li>'."$value".'</li>';
echo '<li><a href="download.php?="' . $value . '>Download</a></li>';
echo '<li>Preview</li></ul>';
$_SESSION['download'] = $value;
}
}
?>
And here is download.php:
<?php
session_start();
$value = $_SESSION['download'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($value));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($value));
?>
As you can see I'm fairly new to php so any help would be great!
Thanks.

The value of $_SESSION['download']; is always the last file on the FTP connection.
Since you are throwing the path via GET, you should use it instead.
Change
$value = $_SESSION['download'];
To
$value = $_GET['download'];

try this :-
echo '<li><a href="download.php?="' . $value . '>Download</a></li>';
change this line to this
echo '<li><a href="download.php?download="' . $value . '>Download</a></li>';
and in the download.php get the value of download like
$value = $_GET['download'];

Related

readfile() method prints file instead of downloading

I want to download a file using PHP from an absolute path using the header() and readfile() methods. It used to work before, but doesn't anymore.
I've tried changing the Content-type, but nothing worked.
$p = $_GET['plugin'];
$v = $_GET['version'];
if (isset($p) && isset($v)) {
if (in_array($p, getPlugins($_SESSION['username']))) {
$url = '/home/uploads/' . $p . '/' . $v . '.jar';
header('Content-Description: File Transfer');
header("Content-type: application/java-archive");
header('Content-Disposition: attachment; filename="' . $p . ' ' . $v . '.jar"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-length: ' . filesize($url));
readfile($url);
//header('Location: plugins.php');
exit();
}
}
It should download the jar file that should be named something like "MyPlugin Snapshot-1.0.0.jar". Instead, it prints the whole jar file to the page (see image)
Try using the following content type:
header("Content-type: application/octet-stream");
Did that do the trick?

Force download attachments from specific folder in a Wordpress

I wanna to add Download link button using
Download
After Searching on the internet I got that code:
$file_obj = new FileData($_REQUEST['id']);
// Added this check to keep unauthorized users from downloading - Thanks to Chad Bloomquist
checkUserPermission($_REQUEST['id'], $file_obj->READ_RIGHT, $file_obj);
$realname = $file_obj->getName();
if (isset($revision_id)) {
$filename = $revision_dir . $request_id . ".dat";
} elseif ($file_obj->isArchived()) {
$filename = $GLOBALS['CONFIG']['archiveDir'] . $_REQUEST['id'] . ".dat";
} else {
$filename = $GLOBALS['CONFIG']['dataDir'] . $_REQUEST['id'] . ".dat";
}
if (file_exists($filename)) {
// send headers to browser to initiate file download
header('Cache-control: private');
header('Content-Type: '.$_GET['mimetype']);
header('Content-Disposition: attachment; filename="' . $realname . '"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($filename);
} else {
echo msg('message_file_does_not_exist');
}
Here $revision_dir = $GLOBALS['CONFIG']['revisionDir'] . '/'. $_REQUEST['id'] . '/';
But I wanna download files from sitename.com/pdm-uploads/
Leave the above code and simply add download in <a> tag.
<a href="<?php echo home_url( '/' ).'path/'. $download->realname ?>" download>Download Now</>

How to stop foreach loop from printing duplicate data?

I am trying to generate unique CSV files from the csv data that I have using the following loop.
$k =1;
foreach ($csv_tbl as $_csv) {
$filename = "Agent_" . $k . ".csv";
$file_path = "agents/$filename";
file_put_contents($file_path, $_csv);
if (file_exists($_csv)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($_csv));
readfile($_csv);
die();
}
$k++;
}
The first file generated is perfect and only has the data it should have i.e the first csv table. The second file has both the first and the second tables this goes on for all my 21 files which means the 21st file will have all the tables.
Visual example of the first two files.
How can I prevent duplicates tables from my csv file?
As your foreach is printing duplicates , it means that your array $csv_tbl contains duplicate values, you can remove duplicate values from array using array_unqiue But also by looking at the screenshots i can see that the callid is different for every record. do your csv contain duplicates?::
$k =1;
$csv_tbl = array_unique($csv_tbl);
foreach ($csv_tbl as $_csv) {
$filename = "Agent_" . $k . ".csv";
$file_path = "agents/$filename";
file_put_contents($file_path, $_csv);
if (file_exists($_csv)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($_csv));
readfile($_csv);
die();
}
$k++;
}

Create downloadable CSV from web search using PHP and mySQL

I am trying to create a CSV file that can be downloaded by the user and not have the data permanently saved on the server.
I am using mySQL and PHP for this page. I get the data in the right format to show up ("echo") on the webpage but not able to get the file to generate/download...maybe I am missing something or looking in the wrong place but any help would be great!
I have been trying several script both my own and others I have found but the one I currently have is below:
$file = 'export';
$colresult = mysql_query("SHOW COLUMNS FROM ".$tbl_name."");
if (mysql_num_rows($colresult) > 0) {
while ($row = mysql_fetch_assoc($colresult)){
$csv_output .= $row['Field'].", "; $i++; } } $csv_output .= "\n";
$csvresult = mysql_query($sql);
while ($rowr = mysql_fetch_row($csvresult)) {
for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n"; }
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/csv");
header("Content-disposition: attachment;filename=".$filename.".csv");
readfile("../documents/csv/".$filename.".csv");
$fp = fopen($filename, 'w');
foreach($csvret as $csvret){
fputcsv($fp, $csvret);
}
print $csv_output;
print $filename;
Thanks!
You'll need to pass some headers to force the web browser to recognize the file as "downloadable":
<?php
header('Content-Description: File Transfer');
header("Content-Type: application/csv");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
Simply add that code in place of:
print $csv_output;
print $filename;

Form downloads same ZIP over and over

Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!

Categories