Sam Brody
Sam Brody

Reputation: 31

PHP force download, download without naming the file the full path name

So our system works by storing user images in in user folders, user folders are stored in master user folders which are stored in one folder called client_folders.

Everytime I try to build our download script (using php force download) the files that get downloaded with the name of the entire file path

Example: client_folder/user_30/client_130/image.jpg

I just want the file to say image.jpg

I have tried several things, explode with array pop, basename() but everytime I try one of these options the variable that the readfile() function reads is empty.

Now in mysql I am storing the entire file path (file name included) in one column, is this the right way to do this? and how to do I download files without the entire path

if it helps this is the code that successfully downloads....just with the full path name :(

ob_clean();
if(isset($_POST['file_name'])){
$file = $_POST['file_name'];
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($file);
exit();
}

Upvotes: 0

Views: 3374

Answers (2)

Sam Brody
Sam Brody

Reputation: 31

If you are dynamically pulling a file for download using a referenced file path from mysql and you want the download to have the files name and not the path here is what you do

ob_clean();
if(isset($_POST['file_name'])){
$file = $_POST['file_name'];
$filename = basename($file);
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($file);
exit();
}

Here is the commented version

//This cleans the cache (just a precaution)
ob_clean();

//Grab the file path from the POST global
if(isset($_POST['file_name'])){

//Put the global variable into a regular variable
$file = $_POST['file_name'];

//Use basename() to separate the name of the file from the reference path and put it in a variable
$filename = basename($file);

//I have no idea if this is needed  but everyone uses it 
header("Content-type: application/octet-stream");

//Use this header to name your file that is being downloaded, use the variable that is storing the file name you grabbed using basename()
header('Content-Disposition: attachment; filename="'.$filename.'"');

//useread file function to send info to buffer and start download, use the variable that contains the full path
readfile($file);
exit();
}

Upvotes: 0

IceManSpy
IceManSpy

Reputation: 1098

In readfile you have to pass full path, but in header in filename file name for user:

ob_clean();
if(isset($_POST['file_name'])){
$file_for_user = $_POST['file_name'];
$full_path_file = "STORAGE_PATH".$file_for_user;
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file_for_user.'"');
readfile($full_path_file);
exit();
}

Upvotes: 5

Related Questions