Home > Back-end >  Excel file gets corrupted when uploading to the server via PHP upload form
Excel file gets corrupted when uploading to the server via PHP upload form

Time:09-12

I have a simple HTML file upload form:

<form enctype="multipart/form-data" method="post">
    <input name="description" type="text">
    <input name="file" type="file">
    <button type="submit">Submit</button>
</form>

When the user submits - it sends an AJAX post request to my php script that is running in an Azure App Service (Azure Function). The PHP script saves the file to the server like this:

<?php
file_put_contents($filename, $data);

This is working perfectly for all files - except .xlsx excel files.

When trying to open the excel file that got saved on the server - I receive the following error in excel: We found a problem with some content in 'test-excel-file.xlsx'. Do you want to try to recover as much as we can?

Anyone have any ideas why the .xlsx file is somehow getting corrupted when being saved to the server? I did some testing and can see that when I open both the original excel file and the newly saved excel file in a text editor - the content is the same. So why is Excel complaining?

In fact, I can create a brand new workbook in excel with a sample row of data - save this file. Then open it in a text editor and copy/paste the contents to a new file and the same error occurs. So I really don't think it's an issue with file_put_contents.

So what is the issue with trying to save Excel (.xlsx) file contents to a new .xlsx file? Anyone have any suggestions? Thank you for your time.

CodePudding user response:

The solution was to not host this PHP script in an Azure Function, because Azure Functions do not expose the $_FILES global. Without access to $_FILES, I had to parse the multipart form request manually, which was somehow corrupting complex files.

So I moved the script over to one of our regular Azure App Service's where I could then access the $_FILES global and didn't need to do any manual parsing of the file contents.

  • Related