Skip to content

Slim 4 download files from the server

In Slim 4, you can download a file from the server by utilizing the Response object and setting the appropriate headers. Here’s an example of how to implement file download functionality in Slim 4:

Create a route to handle the download request:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/download', function (Request $request, Response $response) {
    $filePath = 'path/to/file.txt'; // Replace with the actual file path

    if (file_exists($filePath)) {
        $fileName = basename($filePath);

        $response = $response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Content-Disposition', 'attachment; filename=' . $fileName)
            ->withHeader('Content-Transfer-Encoding', 'Binary')
            ->withHeader('Content-Length', filesize($filePath));

        readfile($filePath);
        
        return $response;
    } else {
        return $response->withStatus(404)->write('File not found');
    }
});

$app->run();

In the above example, we create a route /download that handles the file download. Inside the route callback function, we check if the file exists, and if so, we set the necessary response headers for the file download. The Content-Disposition header is set to attachment, which prompts the browser to download the file instead of displaying it. We also include the file name in the Content-Disposition header.

The Content-Transfer-Encoding the header is set to Binary, and the Content-Length the header is set to the file size. This information helps the browser handle the download properly.

If the file exists, we read the file using readfile() and return the modified response object.

If the file does not exist, we set the response status to 404 (Not Found) and write an error message.

Make sure to adjust the code according to your specific file path and requirements.

When the user visits the /download URL, the file will be downloaded by the browser with the specified file name.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments