The problem:
I am trying to read a binary file from my web server via PHP but it’s coming back with an incorrect encoding (I think, though I can’t be sure).
Why I am doing this is because I want to remove the need for the user to download a file and populate an <input>
, instead I want to automate the process so the file is automatically retrieved via PHP and the contents are processed by the clientside JS. I know this seems counter-intuitive, but it’s a very specific use-case for flashing ESP chips from ESPTool-JS.
Example results:
The reason I think this is an encoding issue is because this is what I get when reading from a localfile (contents truncated):
x01x00x00x00ðx0Fÿ÷littlefs/
And this is what I get when reading the same file from the server:
x01x00x00x00�x0F��littlefs/
My PHP Code
When running locally I am using an <input type="file" />
element and when running on the server I am using this PHP code:
$filePath = "bins/" . $_REQUEST["file"];
if (file_exists($filePath)) {
$fileContents = file_get_contents($filePath);
if ($fileContents === false) {
http_response_code(500);
die('Failed to read file');
}
// Remove BOM if present
$fileContents = preg_replace('/^xEFxBBxBF/', '', $fileContents);
// Set appropriate headers
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
// Output the file contents
echo $fileContents;
} else {
http_response_code(404);
die('File not found');
}
My PHP.ini:
Please note that my PHP.ini file is set to UTF-8 for both the default_charset
and the internal_encoding
settings.
I’ve been battling this for a long time now! Help, pretty please!! ^_^