Search code examples
phpftpresourcesfilestreamfopen

php can't echo stream after ftp_fget


Can't echo a stream after pulling it from a remote server via ftp_fget, but if I write it to a file it's kinda working...

I guess I need something like a fclose and fopen = freopen ? :D

Need to write from cache/buffer, i guess, to filestream .. ?

If I fclose after written to file and fopen it again I can easily echo it.

Not working

    function download (){
     $fs = fopen('php://temp', "w+");
     ftp_fget($this->connection,$fs,$this->targetdir . $name, FTP_BINARY);
     ftp_close($this->connection);
     return $fs;
    }

    echo stream_get_contents(download('file.xml'));

Kinda Working (file contains text, because got auto closed after script execution)

    function download (){
     $fs = fopen('file.xml', "w+");
     ftp_fget($this->connection,$fs,$this->targetdir . $name, FTP_BINARY);
     ftp_close($this->connection);
     echo $fs
     return $fs;
    }

    echo stream_get_contents(download('file.xml')); //still doesn't work

Solution

  • The Solution

    You need to set the pointer back to the beginning after writing.

    Required command: fseek()

    function test (){
        $fs = fopen('php://temp', "w+");
        ftp_fget($this->connection,$fs,$this->targetdir . $name, FTP_BINARY);
        ftp_close($this->connection);
        fseek($fs,0);
        return $fs;
    }