I want to make a php file at plugin root directory by code . Is there some way that plugin could make a php file at root directory . If yes then what is the procedure.


If using Magento 1

Put the below code wherever you want to create a php file in root directory.

      $_dir =  Mage::getBaseDir();  //i.e. /var/www/html/magento
      $_fileName = 'SAMPLE.php';
      $_content = "SAMPLE CONTENT FOR YOUR FILE";
    file_put_contents($_dir. DS . $_fileName, $_content);

}catch(Exception $e){
        echo $e->getMessage();

Note: Make sure you've given permission to the directory where you creating the file.

In case you want to create file in some other directory in Magento 1.x.

Mage::getBaseDir('app')  //i.e. /var/www/html/magento/app
Mage::getBaseDir('media') //i.e. /var/www/html/magento/media
Mage::getBaseDir('design') //i.e. Get design directory path
Mage::getBaseDir('code') //i.e. Gives code directory file path
Mage::getBaseDir('lib') //i.e. Gives lib directory file path
Mage::getBaseDir('skin') //i.e. Gives skin directory file path
Mage::getBaseDir('var') //i.e. Gives var directory file path
Mage::getBaseDir('cache') //i.e. Gives cache directory file path
Mage::getBaseDir('log') //i.e. Gives log directory file path 
  • Thank you for your help . If i write $base_path = Mage::getBaseDir(); it gave me the path of ROOT directory . After this if i write $base_path->writeFile("SAMPLE.php",$contents); It gave an error Fatal error: Uncaught Error: Call to a member function writeFile() on string . Can you please help to fix it ? – Mohammad Hamdan Jan 28 at 5:40
  • 1
    As you using Magento 1, $base_path->writeFile("SAMPLE.php",$contents); is incorrect. Use the above code I mentioned for Magento 1. – Akhil Gupta Jan 28 at 5:46
  • 1
    Thank You ! Your code works for me . You saved my day ! – Mohammad Hamdan Jan 28 at 5:59

If using Magento 2

You can put this code in your plugin to create a file in ROOT directory.

try {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $filesystem = $objectManager->get('Magento\Framework\Filesystem');
    $directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
    $rootDir = $filesystem->getDirectoryWrite($directoryList::ROOT);

    $contents = "YOUR_CONTENT_GOES_HERE";
        catch(Exception $e){
        echo $e->getMessage();

You can also create file in other directories like media, var etc. Have a look at below file:

  • Thank you for your help . Dear i am working in Magento 1.9.4 . Can you please provide the code for magento 1.9 ? – Mohammad Hamdan Jan 25 at 11:21

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.