0

Is there any way to delete files from var directory, if the file name matched with a condition. I need to delete log files based upon given date. Please let me know how to achieve this in magento2?

0

==> Please used below code

NOTE: Please do not use the Object manager

/** * If the external file is in the root folder */

require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


$fileName = "test.txt";
$file = $obj->create('\Magento\Framework\Filesystem\Driver\File');
$varDirectory = $obj->create('\Magento\Framework\Filesystem')->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);
$varRootDir = $varDirectory->getAbsolutePath();
/*echo $varRootDir.$fileName;
die();*/
if ($file->isExists($varRootDir . $fileName))  {
    $file->deleteFile($varRootDir . $fileName);
     echo 'file ('.$varRootDir . $fileName.') delete Succssfully'."\n";
}

I hope this is helpful to you!!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.