I am trying to write a script to check if a file exists or not. If the file exists, start download of file.
$get_file = $_GET['file'];
$file_raw = '/var/www/data.xxxx.com/html/' . $get_file;
$file = str_replace(' ', '\\ ', $file_raw);;
if (!file_exists($file)) { // file does not exist
die('file not found - ' . $file);
} else {
if (file_exists($file)) {
$fileName = basename($file);
$fileSize = filesize($file);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/octet-stream");
header("Content-Length: " . $fileSize);
header("Content-Disposition: attachment; filename=" . $fileName);
// Output file.
passthru("cat $file");
exit();
} else {
die('The provided file path is not valid.');
}
}
The issue I am encountering is if the $_GET request contains a space, I get a file not found. This is why I implemented the str_replace but this also does not help.
My Answer:
Content-Type: application/octet-stream');_ header('Content-Disposition: attachment; filename="' . $fileName . '"');_ header('Content-Length: ' . $fileSize);__ // Output file._ readfile($file);_ exit;_ } else {_ die('file not found - ' . $file);_ }_}
This code should work to download a file with spaces in the filename. The key is to use the `str_replace` function to replace spaces with `\ ` in the file path. This will ensure that the file path is correctly formatted for the `readfile` function to work properly.
Rate this post
3 of 5 based on 7136 votesComments