Magento 2.4.3
Login to ftp and upload file to destination folder
<?php
namespace Seidor\ExportFileSap\Cron;
class Export{
/**
* @var \Magento\Framework\Filesystem\Io\Ftp
*/
protected $ftp;
/**
* @var \Magento\Framework\Filesystem\Io\File
*/
protected $file;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
protected $driverFile;
/**
* @param \Magento\Framework\Filesystem\Io\Ftp $ftp
* @param \Magento\Framework\Filesystem\Io\File $file
* @param \Magento\Framework\Filesystem\Driver\File $driverFile
*/
public function __construct(
\Magento\Framework\Filesystem\Io\Ftp $ftp,
\Magento\Framework\Filesystem\Io\File $file,
\Magento\Framework\Filesystem\Driver\File $driverFile
){
$this->ftp = $ftp;
$this->file = $file;
$this->driverFile = $driverFile;
}
public function execute()
{
$debugStep = '0';
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/debug_payment_method.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info(__FILE__."::".__LINE__);
$logger->info('Ha habido un problema al cargar');
$ftp_path = 'pendientes';
$open = $this->ftp->open(
array(
'host' => 'ftp.server.com',
'user' => 'USERNAME',
'password' => 'PASSWORD',
'ssl' => true,
'passive' => true
)
);
/**
* first connect to ftp server
*/
$debugStep .= '1';
if (!$open)
{
die("FTP Connection Failed");
$logger->info('FTP Connection Failed Cron');
}
/**
* upload all file from var/tmp/order dir
*/
$debugStep .= '2';
$files = $this->driverFile->readDirectory(BP.'/var/tmp/order/');
foreach($files as $file) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if($ext == 'csv'){
$content = $this->file->read($file);
$filename = pathinfo($file, PATHINFO_BASENAME);
if ($this->ftp->write($ftp_path.'/'.$filename, $content))
{
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/logListadoCsv.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info(__FILE__."::".__LINE__);
$logger->info('Cargado correctamente:'.$file);
$this->file->rm($file);
$debugStep .= '3';
} else {
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/logNotUploadFile.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
$logger->info(__FILE__."::".__LINE__);
$logger->info('Ha habido un problema al cargar:'.$filename);
$debugStep .= '4';
}
}
}
$this->ftp->close();
$debugStep .= '5';
if (date('H') == 4 && date('i') >= 00 && date('i') < 11) {
//Vaciamos el registro de la factura que se ha generado diariamente para que no llenar memoria
$this->file->rm("var/log/billings.txt");
$debugStep .= '6';
}
return $debugStep;
}
}