I’m having trouble downloading a file through slim, in the images below, the file on the left the original .tmp file on the server and on the right the file after down using the class below.
Regardless of the class if I put a txt content to download the same problem also occurs, it seems that it puts an empty space at the beginning of the file and removes the last character.
The strange thing and that this happens in some servers and others not, windows servers with Apache 2.4.47 Handler + PHP 7.3.28
<?php
$response->getBody()->write($nfse->xml);
return $response->withHeader('Content-Type', 'application/xml')
->withHeader('Content-Disposition', 'attachment;filename="' . $nfse->name . '.xml"');
<?php
/**
* Created by PhpStorm.
* User: Elvis
* Date: 20/04/2017
* Time: 06:29
*/
namespace App\Helper;
use Psr\Http\Message\ResponseInterface as Response;
use GuzzleHttp\Psr7\LazyOpenStream as Stream;
class FileResponse
{
/**
* @param Response $response
* @param string|Stream $file
*
* @param null $outputName
* @return Response
*/
public static function getResponse(Response $response, $file, $outputName = null): Response
{
if (is_string($file)) {
$stream = new Stream($file, 'rb');
} else {
$stream = $file;
}
$path_parts = pathinfo($stream->getMetadata('uri'));
$ext = strtolower($path_parts["extension"]);
if (!$outputName) {
if ($ext === 'tmp') {
$content_type = mime_content_type($path_parts["dirname"] . DS . $path_parts["basename"]);
if ($content_type === 'application/zip') {
$ext = 'zip';
}
}
$outputName = $path_parts["filename"] . '.' . $ext;
} else {
if (count(explode('.', $outputName)) <= 1) {
$outputName = $outputName . '.' . $ext;
}
}
switch ($ext) {
case "pdf":
$type = "application/pdf";
break;
case "xml":
$type = "application/xml";
break;
case "png":
$type = "image/png";
break;
case "gif":
$type = "image/gif";
break;
case "jpeg":
$type = "image/jpeg";
break;
case "jpg":
$type = "image/jpg";
break;
case "mp3":
$type = "audio/mpeg";
break;
case "zip":
$type = "application/zip";
break;
case "doc":
$type = "application/msword";
break;
case "docx":
$type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
break;
case "xls":
$type = "application/vnd.ms-excel";
break;
case "xlsx":
$type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
default;
$type = "application/octet-stream";
break;
}
return $response->withHeader("Content-type", $type)
->withHeader("Content-Disposition", 'filename="' . $outputName . '"')
->withHeader("Cache-control", "private")
->withHeader("Content-length", $stream->getSize())
->withBody($stream);
}
}