OpenSwoole\Http\Response->sendfile()

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Http\Response->sendfile(string $fileName, int $offset = 0, int $length = 0): bool

Parameters

fileName

The local file path location to be sent. If there is no file found, the sendfile will fail.

offset

The start of file to send, by default it is the beginning of the file

length

The length of data to send. The default value is the whole length of file.

Return

bool

If successful, true is returned otherwise false

Description

Send a local server file directly to HTTP client with sendfile.

Before the call of this method, it is recommended to have set the file content type with $response->header('Content-Type', ...). Swoole does not guess the file type, you have to provide it using HTTP headers instead.

The offset feature is good for when you want to resume a file download if it gets interrupted or the client pauses data transmission.

Important Considerations

Before the call of this method, your must not call $response->write

After the call of this method, $response->end() is called automatically, the response is terminated.

$response->sendfile doesn't support gzip or HTTP compression.

Example

<?php

$server->on('Request', function(OpenSwoole\Server\Request $request, OpenSwoole\Server\Response $response)
{
  $response->header('Content-Type', 'image/jpeg');
  $response->sendfile(__DIR__ . $request->server['request_uri']);
});
Last updated on September 20, 2022