Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a php script that executes Python scripts for the desired excel workbook uploaded from a HTML by user interface, the script work fine, but when I am using readfile() function to download the current file after its being processed, I am facing issues trying to open it, (file format of file extension is not valid)

the result excel file size seems to be correct along with the extension, how every I am still facing this issue bellow you can find my script:

Note that office 365 is installed in both server and my pc.

<?php

ini_set('max_execution_time', 400);

if(isset($_POST['upload'])) {
    $targetDir = "C:\\SSProcess\\ExcelFiles\\"; // Modified target directory path

    // Ensure the directory exists
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $excel_path = $targetDir . basename($_FILES["excelFile"]["name"]);
    $fileType = strtolower(pathinfo($excel_path, PATHINFO_EXTENSION));

    if ($fileType != "xls" && $fileType != "xlsx") {
        echo "Only Excel files are allowed.";
        exit();
    }

    if (move_uploaded_file($_FILES["excelFile"]["tmp_name"], $excel_path)) {
        echo "The file ". basename( $_FILES["excelFile"]["name"]). " has been uploaded.";
        echo "file path = ", $excel_path, "   ."; 
		
        // Execute VBScript using cscript from cmd with admin privileges
        //$vbscript = "C:\\SSProcess\\Scripts\\200-Full_Sheet_Extract.vbs";
        //$cmd_command = "runas /user:FPG\\bot_runner2 \"cmd /c cscript \\\"" . $vbscript . "\\\"\"";
        //exec($cmd_command, $vbscript_output, $vbscript_return_code);

        
        // Execute DuplicatedPerType.py with the uploaded file as an argument
        $pythonScript1 = "C:/Users/bot_runner2/AppData/Local/Programs/Python/Python310/python.exe C:/Users/bot_runner2/Desktop/SS/Script/DuplicatedPerType.py " . escapeshellarg($excel_path);
        exec($pythonScript1, $output1, $returnCode1);

        // Check if DuplicatedPerType.py executed successfully
        if ($returnCode1 === 0) {
            echo "DuplicatedPerType.py executed successfully.";       

            // Execute Type&SubType.py (enclose path in double quotes)
            $pythonScript2 = "C:/Users/bot_runner2/AppData/Local/Programs/Python/Python310/python.exe \"C:/Users/bot_runner2/Desktop/SS/Script/Type&SubType.py\" " . escapeshellarg($excel_path);
            exec($pythonScript2, $output2, $returnCode2);

            // Check if Type&SubType.py executed successfully
            if ($returnCode2 === 0) {
                echo "Type&SubType.py executed successfully.";

                // Copy the Excel file to the ProcessedFiles directory
                $newDir = "C:\\SSProcess\\ProcessedFiles\\"; // New directory path
                $newExcelPath = $newDir . basename($_FILES["excelFile"]["name"]);

                // Ensure the new directory exists
                if (!file_exists($newDir)) {
                    mkdir($newDir, 0777, true);
                }

			// Copy the file
			if (copy($excel_path, $newExcelPath)) {
				echo "Excel file copied successfully.";
				sleep(3);

				// Set the appropriate Content-Type header for .xlsx files
				header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

				// Set Content-Disposition header to force download with the correct filename
				header("Content-Disposition: attachment; filename=\"" . basename($newExcelPath) . "\"");

				// Output the file contents
				readfile($newExcelPath);
				exit();
			} else {
				echo "Failed to copy Excel file.";
			}


            // Redirect back to SystemSummary.html
            //header('Location: http://10.1.4.63:8080/HTML/SystemSummary.html');
            //exit();
            } else {
                echo "Error executing Type&SubType.py.";
                // You can handle errors here
            }
        } else {
            echo "Error executing DuplicatedPerType.py.";
            // You can handle errors here
        }
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>


What I have tried:

i have tried setting the appriopriate contect-type header for xlsx files.
Posted
Comments
Pete O'Hanlon 1-Apr-24 6:49am    
When you download the file, what file name do you see?
Abed Al Rahman Hussien Balhawan 1-Apr-24 6:54am    
when I download the file I see the size is correct. The extension type too, however when I try to access it returns a warning message(Excel cannot open the file 'generated_BOQ1.xlsx'because the file format or file extension is not valid, verify that the file has not been corrupted and that the file extension matches the format of the file.)
Dave Kreskowiak 1-Apr-24 8:26am    
The error is telling you the file isn't a valid Excel file. So go back to whatever code generated this file and look for the problems there.
Abed Al Rahman Hussien Balhawan 1-Apr-24 9:01am    
Hello Pete, the code that generates this file is working fine, the file is also working fine in the server, only when using the readfile function this Is happening.
Pete O'Hanlon 2-Apr-24 2:35am    
I'm glad to see that you sorted the problem. Just a small note - as you didn't reply to my messages, I didn't receive any notifications. If you want to reply to someone, click Reply on their message, don't post a new one that isn't connected.

1 solution

i have figured it out, by applying

ob_clean(); // Clean the output buffer
flush(); // Flush the output buffer

before calling readfile().
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900