OpenSwoole\Coroutine\Http\Client->download(...)

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

Declaration

<?php OpenSwoole\Coroutine\Http\Client->download(string $path, string $filename, int $offset = 0): bool

Parameters

path

The path of the remote file to be downloaded. For example /images/swoole-logo.svg. Only set the path here not the protocol or domain name like http://domain.

filename

The absolute filepath of where to download the file to, locally.

offset

The offset of the remote file to be downloaded. The offset can be used to support resumable file downloads with the HTTP header Range:bytes=$offset.

Return

On success true is returned or else false which means something went wrong. Make sure you have correct file permissions and disk space. Check $client->errCode to see what went wrong.


Description

Download a file from the remote server.

The difference between the download method and the get method is that the download method will write the data to the disk after receiving the data instead of splicing the HTTP Body into memory. Therefore, downloading a file only uses a small amount of memory to complete a download of very large files.

An offset of 0 (default) means the beginning of the file, if the file already exists then the file will be overwritten.


Example

<?php
use OpenSwoole\Coroutine\HTTP\Client;

co::run(function()
{
    $host = 'openswoole.com';

    // Connect via SSL
    $client = new OpenSwoole\Coroutine\Http\Client($host, 443, true);

    $client->set(['timeout' => -1]);

    $client->setHeaders([
        'Host' => $host,
        "User-Agent" => 'Chrome/49.0.2587.3',
        'Accept' => '*',
        'Accept-Encoding' => 'gzip'
    ]);

    // Download the OpenSwoole Logo within the current directory
    $downloadStatus = $client->download('/images/swoole-logo.svg', __DIR__ . '/swoole-logo.svg');

    echo "Download Status: $downloadStatus\n";

    if(file_exists(__DIR__ . '/swoole-logo.svg'))
    {
      // ...
    }
    else
    {
      // ...
    }

    $client->close();
});
Last updated on September 1, 2022