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?

1 Answer 1


==> 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');

$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;
if ($file->isExists($varRootDir . $fileName))  {
    $file->deleteFile($varRootDir . $fileName);
     echo 'file ('.$varRootDir . $fileName.') delete Succssfully'."\n";

I hope this is helpful to you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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