PHP file download returns 0 size when uploading specific file

Viewed 55

I have a PHP code that lets the user upload and download a file using REST api. When I do upload some files and download it thru the endpoint, there is no issue encountered (Im not sure since there are many file extensions but the common ones has no issues). But when I try to upload an .sql file which I exported from the database, the upload function doesnt have a problem but when I try to download it, the size goes randomly into 0 - 1kb then when I open the sql file what I get is like this. I also tried to compress the sql file but after downloading, i cannot open and it is saying the file is corrupted or something.

<br />
<b>Warning</b>:  readfile(http://localhost/mtc_project_server/files/mtc_project (1).sql): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
 in <b>C:\xampp\htdocs\mtc_project_server\models\DataFile.php</b> on line <b>111</b><br />

Here is my function for uploading and downloading file.

    public function uploadFile($param,$file){
        $upload_path = '../files/';
        $temp_path = $file['tmp_name'];
        if (file_exists($upload_path . $file['name'])) {
            unlink($upload_path . $file['name']);
        }

        if(move_uploaded_file($temp_path,$upload_path.$file['name'])){
            $this->setFileQuery($param,$file);
        }else{
            Responses::http_error();
        }
        
    }

For downloading

    public function downloadFile($param){
        $base_url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
     
        $q = "SELECT * FROM data_file WHERE module_id = ". $param;
        $stmt = $this->conn->prepare($q);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!empty($row)){
            $filename = $row['file_name'];
            $request_url = $base_url .'/mtc_project_server/files/'.$filename;
            header('Content-Type: application/octet-stream');
            header("Content-Transfer-Encoding: Binary"); 
            header("Content-disposition: attachment; filename=\"" . basename($request_url) . "\""); 
            readfile($request_url); 
            exit();

            $date = date('Y-m-d H:i:s');
            $update = "UPDATE server_status SET file_start = ?, file_start_time = ? WHERE module_id = " .$param;
            $updateStmnt2 = $this->conn->prepare($update);
            $updateStmnt2->execute([
                2,
                $date
            ]);
        }else{
            Responses::http_not_found();
        }

0 Answers
Related