phpftpin-memorydbase

PHP: how to write a dBase file from memory to FTP


I want to save a dBase file on a ftp server directly from memory. I use the following simplified snippet. The dBase file is also stored on the server - but it is empty.

What have I done wrong?

Is there a way to do that without first saving the file locally and then transferring it via ftp?

$ftp_conn = ftp_connect($ftpserver);
ftp_login($ftp_conn, $user, $password);
ftp_chdir($ftp_conn, $destination);
$memstream = fopen('php://memory', 'r+');
if ($myClass->create($memstream)) {       // my function around dbase_create() 
    $numRecords = count($myData); 
    if ($numRecords) {
        $myClass->open();                 // my function around dbase_open()
        foreach ($myData as $myRec) {
            $myClass->addRecord($myRec);  // my function around dbase_add_record()
        }
        $myClass->close();                // my function around dbase_close()
        /** the following lines are for debugging
          * they are delivering correct data -
          * so there is still access to the dBase file 
          **/
        $fritzAdr->open();
        print_r($fritzAdr->getRecord(1);
        $fritzAdr->close();
        $fritzAdr->open();
        print_r($fritzAdr->getRecord($fritz->countRecords())
        $fritzAdr->close();
        // but the $memstream is empty!
        rewind($memstream);
        ftp_fput($ftp_conn, 'filename.dbf',  $memstream, FTP_BINARY);
    }
fclose($memstream);
ftp_close($ftp_conn);

Solution

  • At the end I have written my own class, which can generate the desired dBase III file: https://github.com/BlackSenator/fritzadr and it worked in the desired way:

    $memstream = fopen('php://memory', 'r+');
    if ($numRecords) {
        $fritzAdr = new fritzadr();
        foreach ($faxContacts as $faxContact) {
            $fritzAdr->addRecord($faxContact);
        }
        fputs($memstream, $fritzAdr->getDatabase());
        rewind($memstream);
        ftp_fput($ftp_conn, 'fritzadr.dbf', $memstream, FTP_BINARY);
    }
    fclose($memstream);
    ftp_close($ftp_conn);