In this article, you going to see a discussion regarding Magento 2 Check File Exists Programmatically in a detail and step by step in a simple way.
If you are looking for this topic then you are at a right place.
Let’s start with the topic of Magento 2 Check File Exists Programmatically.
It is very simple to check the file is exists at a specific location in case of Magento 2.
For checking whether the file is exists is possible with help of class file.
Below you will see the path of file.
Using this class file you can check the file is present at specific location or not.
Class file is present in the Magento 2 directory are as follow.
Magento\Framework\Filesystem\Driver\File.
Using this file you can check the file exist or not instead of using the PHP core method.
Using Block file you can do this.
You have create function inside it using constructor DI for checking whether the file is exists or not.
Due to which, it’s become very easy to check the file is present at specific location or not.
Using below code snippet you come to understand how to check the file exists or not.
Please check with the below code snippet.
<?php
namespace Techone\FiletoCheck\PathtoBlock;
class FileCheckDemo extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Filesystem\Driver\File $fileDriver,
array $data = []
) {
$this->fileDriver = $fileDriver;
parent::__construct($context,$data);
}
/**
* Check file is exist or not at specific location
*/
public function checkFileExists()
{
$fileName = '/var/www/html/magento2/var/log/system.log';
if ($this->fileDriver->isExists($fileName)) {
return "file is exist";
} else {
return "file not exist";
}
}
Next step is to use this code snippet in the template file.
You have to just call this block method in template file.
Below is code snippet how to call this in template file.
echo $block->checkFileExists();
In the check file exists method you just have to pass the path of file for checking file is present at specific location or not.
In this case, i used system log file which is present in var folder.
You can use any file as per you requirement.
Magento 2 Get Product Image Url in phtml
Conclusion :
I hope you like this article and if you think that i have missing something, please comment below.