Çıkış Stream FTP indir

6 Cevap php

Ben FTP, HTTP üzerinden kullanıcının tarayıcısına / Boru bir dosya akışı için çalışıyorum. Ben bir FTP sunucusunda bir dosyanın içeriğini yazdırmak için çalışıyorum, olduğunu.

Bu ben bugüne kadar ne var:

public function echo_contents() {                    
    $file = fopen('php://output', 'w+');             

    if(!$file) {                                     
        throw new Exception('Unable to open output');
    }                                                

    try {                                            
        $this->ftp->get($this->path, $file);         
    } catch(Exception $e) {                          
        fclose($file);  // wtb finally               

        throw $e;                                    
    }                                                

    fclose($file);                                   
}

$this->ftp->get bu gibi görünüyor:

public function get($path, $stream) {
    ftp_fget($this->ftp, $stream, $path, FTP_BINARY);  // Line 200
}

Bu yaklaşımla, sadece kullanıcının tarayıcısına küçük dosya göndermek mümkün duyuyorum. Büyük dosyalar için, hiçbir şey basılmış olur ve ben (Apache günlükleri okunabilir) önemli bir hata alıyorum:

PHP Fatal error: / xxx / ftpconnection.php bitkin 16777216 bayt İzin bellek boyutu hattında 200 (15.994.881 bayt ayırmaya çalıştı)

Ben (bir şey tarayıcınıza gönderilen görünüyor) başarı olmadan php://output php://stdout ile değiştirmeyi denedim.

Aynı anda tarayıcı bu verileri gönderirken Nasıl verimli FTP indirebilirsiniz?

Note: I would not like to use file_get_contents('ftp://user%3Apass@host%3Aport/path/to/file '), or similar.

6 Cevap

Bir çözüm buldu!

Bir soket çifti oluşturma (anonim boru?). Borunun bir ucuna yazmak için engellenmeyen ftp_nb_fget işlevini kullanın ve borunun echo diğer ucu.

fast (100Mbps bağlantı kolayca 10MB / s) olarak test çok I / O havai yok.

Be sure to clear any output buffers. Frameworks commonly buffer your output.

public function echo_contents() {
    /* FTP writes to [0].  Data passed through from [1]. */
    $sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

    if($sockets === FALSE) {
        throw new Exception('Unable to create socket pair');
    }

    stream_set_write_buffer($sockets[0], 0);
    stream_set_timeout($sockets[1], 0);

    try {
        // $this->ftp is an FtpConnection
        $get = $this->ftp->get_non_blocking($this->path, $sockets[0]);

        while(!$get->is_finished()) {
            $contents = stream_get_contents($sockets[1]);

            if($contents !== false) {
                echo $contents;
                flush();
            }

            $get->resume();
        }

        $contents = stream_get_contents($sockets[1]);

        if($contents !== false) {
            echo $contents;
            flush();
        }
    } catch(Exception $e) {
        fclose($sockets[0]);    // wtb finally
        fclose($sockets[1]);

        throw $e;
    }

    fclose($sockets[0]);
    fclose($sockets[1]);
}

// class FtpConnection
public function get_non_blocking($path, $stream) {
    // $this->ftp is the FTP resource returned by ftp_connect
    return new FtpNonBlockingRequest($this->ftp, $path, $stream);
}

/* TODO Error handling. */
class FtpNonBlockingRequest {
    protected $ftp = NULL;
    protected $status = NULL;

    public function __construct($ftp, $path, $stream) {
        $this->ftp = $ftp;

        $this->status = ftp_nb_fget($this->ftp, $stream, $path, FTP_BINARY);
    }

    public function is_finished() {
        return $this->status !== FTP_MOREDATA;
    }

    public function resume() {
        if($this->is_finished()) {
            throw BadMethodCallException('Cannot continue download; already finished');
        }

        $this->status = ftp_nb_continue($this->ftp);
    }
}

Deneyin:

@readfile('ftp://username:password@host/path/file'));

Ben altta yatan OS işlevselliği sizin için ilgilenir icar faydalıdır dosya işlemleri bir sürü bulabilirsiniz.

PHP tüm belleğe sığdırmak için çalışacağız, aksi takdirde, o sayfa için çıkış tamponu kapatır gerekir gibi geliyor.

Bunu yapmanın kolay bir yolu gibi bir şeydir:

while (ob_end_clean()) {
    ; # do nothing
}

O önde çağrı koy -> (olsun), ve ben bu sorunu çözeceğini düşünmek.

Bir hızlı arama php flush kadar getirdi.

bu yazı da ilgi olabilir: http://www.net2ftp.org/forums/viewtopic.php?id=3774

(I've never met this problem myself, so that's just a wild guess ; but, maybe... )

Belki "dosyası" için çıkışına tampon boyutunu değiştirerek size yardımcı olabilir için yazıyoruz?

Bunun için, stream_set_write_buffer bakın.

Örneğin:

$fp = fopen('php://output', 'w+');
stream_set_write_buffer($fp, 0);

Bu ile, kod olmayan bir tamponlu akışı kullanmalısınız - bu yardımcı olabilir ...

Ben bu eski olduğunu biliyorum, ama bazıları hala yararlı olduğunu düşünebilirler.

Ben bir Windows ortamında üzerinde çözümü denedim, ve almost mükemmel çalıştı:

$conn_id = ftp_connect($host);
ftp_login($conn_id, $user, $pass) or die();

$sockets = stream_socket_pair(STREAM_PF_INET, STREAM_SOCK_STREAM,
        STREAM_IPPROTO_IP) or die();

stream_set_write_buffer($sockets[0], 0);
stream_set_timeout($sockets[1], 0);

set_time_limit(0);
$status = ftp_nb_fget($conn_id, $sockets[0], $filename, FTP_BINARY);

while ($status === FTP_MOREDATA) {
    echo stream_get_contents($sockets[1]);
    flush();
    $status = ftp_nb_continue($conn_id);
}
echo stream_get_contents($sockets[1]);
flush();

fclose($sockets[0]);
fclose($sockets[1]);

I STREAM_PF_INET yerine çünkü Windows'un STREAM_PF_UNIX kullanılan ve hiçbir belirgin nedenle false oldu son öbek kadar ... kusursuz çalıştı ve ben neden anlayamadım. Yani çıkış son bölümünü eksikti.

Yani başka bir yaklaşım kullanmaya karar verdim:

$ctx = stream_context_create();
stream_context_set_params($ctx, array('notification' =>
        function($code, $sev, $message, $msgcode, $bytes, $length) {
    switch ($code) {
        case STREAM_NOTIFY_CONNECT:
            // Connection estabilished
            break;
        case STREAM_NOTIFY_FILE_SIZE_IS:
            // Getting file size
            break;
        case STREAM_NOTIFY_PROGRESS:
            // Some bytes were transferred
            break;
        default: break;
    }
}));
@readfile("ftp://$user:$pass@$host/$filename", false, $ctx);

Bu PHP 5.4.5 ile bir cazibe gibi çalıştı. Kötü bölümü aktarılan verileri, sadece bir yığın boyutunu yakalamak değil olmasıdır.