Download with Custom Name

Got something cool to share with AppGini users? Feel free to post it here!
Post Reply
User avatar
onoehring
AppGini Super Hero
AppGini Super Hero
Posts:1464
Joined: 2019-05-21 22:42
Location: Germany
Contact:

Download with Custom Name

Post by onoehring » 2026-03-10 11:00

Hi,

I present a small fix that might help one or the other: Custom Download names

Purpose
AppGini is able to make sure names of uploaded files (and images) are not overwritten if you disable keeping the filename.
This however turns out to be ugly when the user downloads a file again.

I present adjustments to make custom download names possible. These are pulled from another column of the table.

As this uses a different technique than AG itself uses, it could be possible (yet untested) to use this to pull content from a folder outside webroot.

Disclaimer
a. Use at your own risk.
b. make a backup of all files and your database before you start
c. Make sure to
a. read AND
b. understand the documentation in the beginning of this file AND
c. implement necessary adjustments in your application AND
d. that you make necessary adjustments in the adjustment-area below

THIS SCRIPT HAS BEEN TESTED AND THE INSTALLATION EXPLANATION HAS BEEN CHECK REPEATEDLY, BUT THERE COULD BE AN ERROR.
ALSO, YOU MAY MAKE AN ERROR IMPLEMENTING THE SCRIPT.
YOU ARE ON YOUR OWN AND IT IS SOLELY YOUR RESPONSIBILITY! NO HELP CAN BE EXPECTED, NO GUARANTEE CAN BE GIVEN!

Installation
IMPORTANT: BACKUP YOUR APPLICATION BEFORE YOU START!

General Config
ATTENTION: You will need to repeat THIS change to link.php EVERY time you regenerate your application!

10) open /link.php
In the beginning of the file you find something like this:

Code: Select all

// Upload paths
$p = [
    'tbldocuments' => [
        'filename_uploaded' => getUploadDir(''),
        'primary key' => 'id'
    ],
];
This lists all tables (here only one: tbldocuments) and the field which holds the name of the uploaded file (here: filename_uploaded) and the name of the primarey key of the table (here: id).
For each table add the following line after the table name.
Add

Code: Select all

'downloadFilename' => 'filename_original',   // add the fieldname under which the file should be downloaded to the user
so that the above example would result in this:

Code: Select all

// Upload paths
$p = [
    'tbldocuments' => [
        'downloadFilename' => 'filename_original',   // add the fieldname under which the file should be downloaded to the user
        'filename_uploaded' => getUploadDir(''),
        'primary key' => 'id'
    ],
];
Note: for each table that allows to upload files (or images) you need to replace filename_original with the actual fieldname in that table that holds your desired “download name” (when the user downloads the file by clicking on it). If a table does not have this, you still need to add the line like this:

Code: Select all

'downloadFilename' => '',   // add the fieldname under which the file should be downloaded to the user
15) Search and replace

Code: Select all

getLink($t, $f, $p[$t]['primary key'], $i, $p[$t][$f]);
replace with

Code: Select all

getLink($t, $f, $p[$t]['primary key'], $i, $p[$t][$f], $p[$t]['downloadFilename']);
20) Search and replace

Code: Select all

function getLink($table = '', $linkField = '', $pk = '', $id = '', $path = '') {
replace with

Code: Select all

function getLink($table = '', $linkField = '', $pk = '', $id = '', $path = '', $downloadFilename = '')
30) Search and replace
(complete IF statement)

Code: Select all

    if(preg_match('/^(http|ftp)/i', $link)) {    // if the link points to an external url, don't prepend path
        $path = '';
    } elseif(!is_file(__DIR__ . "/{$path}{$link}")) {    // if the file doesn't exist in the given path, try to find it without the path
        $path = '';
    }
replace with

Code: Select all

// Correcting how we set the path for local files
if (preg_match('/^(http|ftp)/i', $link)) {    // If the link points to an external URL, don't prepend path
    $path = '';
} else {
    // Construct the full path
    $fullPath = __DIR__ . "/{$path}{$link}";
    if (!is_file($fullPath)) {    // If the file doesn't exist in the given path, try to find it without the path
        exit("File not found. Fullpath: '$fullPath'");
    }
}
40) Search and replace
Note: include the } in the end! This search should be in the end of the file.

Code: Select all

		@header("Location: $path$link");
		exit;
	}
Replace with

Code: Select all

    // Assuming you want to define a filename for downloads
    // try custom name
    $filename = getDownloadFilename($table, $pk, $id, $downloadFilename);
    // fallback
    if ($filename == '') {
        $filename = basename($link);  // Change this if you'd like a custom name
    }
    sendFile($fullPath, $filename);
    exit;
}
/**
 * read the name for the file that should be given to download
 * @param mixed $table
 * @param mixed $pk
 * @param mixed $id
 * @param mixed $downloadFilename
 * @return string
 */
function getDownloadFilename($table = '', $pk = '', $id = '', $downloadFilename = ''): string
{
    $sql = "SELECT `$downloadFilename` FROM `$table` WHERE `$pk` = '$id';";
    $result = sqlvalue($sql);

    // Corrected comparison
    if (is_null($result) || (strlen($result) == 0)) {
        // Fallback
        $result = '';
    }

    return $result;
}


function sendFile($filePath, $filename)
{
    // Check if file exists
    if (!file_exists($filePath)) {
        exit("File not found. Path '$filePath', File: '$filename'");
    }

    // Set headers for file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filePath));

    // Clear output buffer and read the file
    ob_clean();
    flush();
    readfile($filePath);
    exit;
}
Uninstall
Regenerate your application (or replace the changed link.php with the original).

Comments? Suggestions?

Olaf

Post Reply