In this article, we are going to teach you how can you check file exists or not programmatically in Magento 2 step by step in a simple Method.
Step 1: You need to create a block file in your custom module
path – app/code/Webiators/FileExists/Block/CheckFileExists.php
and add this code given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace Webiators\FileExists\Block; use Magento\Framework\View\Element\Template\Context; class CheckFileExists extends \Magento\Framework\View\Element\Template { protected $_storeManager; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Filesystem\Driver\File $fileDriver, \Magento\Store\Model\StoreManagerInterface $storeManager, array $data = [] ) { $this->fileDriver = $fileDriver; $this->_coreRegistry = $registry; $this->_storeManager = $storeManager; parent::__construct($context,$data); } /** * Check file is exist or not at specific location */ public function checkFileExists() { $fileName = '/home/devweb/shop.dev.webiators.com/pub/media/webiators/myfile.pdf'; if ($this->fileDriver->isExists($fileName)) { return "file is exist"; } else { return "file not exist"; } } } |
Step 2: After creating the block file you need to create a template file customfile.phtml path:
app/code/Webiators/FileExists/view/frontend/templates/html/customfile.phtml and call the block function in this template file
1 2 3 4 5 6 |
<?php echo $block->checkFileExists(); ?> |
Step 3: You need to create a default layout default.xml file path:
app/code/Webiators/FileExists/view/frontend/layout/default.xml and call block and template file in this layout file
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <page layout="3columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="after.body.start"> <block class="Webiators\FileExists\Block\CheckFileExists" name="store-custom" before="before.body.end" template="Webiators_FileExists::html/customfile.phtml"/> </referenceContainer> </body> </page> |
Now check the result on the frontend.
Thank You!
Read More