1

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.

NickyTheWrench
  • 3,150
  • 1
  • 23
  • 35
  • Try to open the file with a hex editor and compare the files. There are most probably some characters which are missing/extra in the corrupted file – Cornel Raiu Sep 09 '22 at 21:09
  • 1
    Why are you using `file_put_contents`. Wouldn't `move_uploaded_file` be a better solution? – Guido Faecke Sep 09 '22 at 21:09
  • Does this answer your question? [Why is my docx, xlsx, pptx file corrupted?](https://stackoverflow.com/questions/24557994/why-is-my-docx-xlsx-pptx-file-corrupted) – Cornel Raiu Sep 09 '22 at 21:11
  • @GuidoFaecke Normally yes, but can't use that because of the way Azure handles the incoming request. – NickyTheWrench Sep 10 '22 at 00:09
  • If you save your file as "xls" (excel 97/2003 format) and upload the file, what happens ? (will it still get corrupted ?) – Ken Lee Sep 10 '22 at 01:48

1 Answers1

0

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.

NickyTheWrench
  • 3,150
  • 1
  • 23
  • 35