I have a simple php form that I use to upload and store files.
It's basically working via MySQL, Apache, and php.
I have upload.php which file I use to upload files in directory of the project rootdir/uploads
I am renaming the file during the uploading via php script and storing the filename in MySQL table. Here is part of the code for renaming and uploading the file:
$upload_dir = 'uploads/';
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION); filename
$new_file_name = $docnr . '.' . $file_extension;
$upload_path = $upload_dir . $new_file_name;
if (move_uploaded_file($file_tmp_name, $upload_path)) {...........
The form is working, and files are renamed and uploaded correctly but after this, I have download.php file which I use to download files. here is the code of download.php
`<?php
include ('dbconn.php');
$id = $_GET['id'];
$query = "SELECT * FROM documents WHERE id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
header('Content-Disposition: attachment; filename="'.$row['file_name'].'"');
readfile($row['file_path']);
?>
`
THE problem: when I download for example uploaded Excel file, the file is corrupted and cannot be opened anymore, but if I navigate through the browser to rootdir/uploads and download the file from there via clicking the downloaded file is not corrupted and is working fine. Tell me what I am doing wrong.
I had .htaccess file with deny from all
in order to try protecting visiting /uploads
via browser, I thought that this could be the problem and I deleted .htaccess but this not solved my issue.
Update: download.php code updated in order to fix security weaknesses. When I download for example .txt file via download.php and open it via notepad++ inside the download file I have this:
<br />
<b>Warning</b>: Undefined array key "file_path" in <b>C:\xampp\htdocs\ottodoc\download.php</b> on line <b>22</b><br />
<br />
<b>Fatal error</b>: Uncaught ValueError: Path cannot be empty in C:\xampp\htdocs\ottodoc\download.php:22
Stack trace:
#0 C:\xampp\htdocs\ottodoc\download.php(22): readfile('')
#1 {main}
thrown in <b>C:\xampp\htdocs\ottodoc\download.php</b> on line <b>22</b><br />
when I open the file directly from the browser via http://localhost/ottodoc/uploads/file.txt is fine. Obviously, something is wrong with my download.php which I cannot catch.
``` I am missing something but where... – Qbasix May 09 '23 at 06:52