Hello magento friends todays in this blog post im share with you to How to Create a Directory Programmatically in Magento 2
In Magento 2, you can create a directory programmatically using PHP code. Here's a step-by-step guide on how to achieve this:
➤ First, create a new PHP file in the root directory of your Magento 2 installation. You can name it create_directory.php or anything you prefer.
➤ Add the following code to the create_directory.php file:
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
// Replace 'custom_directory' with the desired name of your directory
$directoryName = 'custom_directory';
// Get the base directory path
$baseDir = $objectManager->get('Magento\Framework\Filesystem\DirectoryList')->getRoot();
// Check if the directory already exists
if (!file_exists($baseDir . '/' . $directoryName)) {
// Create the directory if it doesn't exist
mkdir($baseDir . '/' . $directoryName);
echo 'Directory "' . $directoryName . '" created successfully.';
} else {
echo 'Directory "' . $directoryName . '" already exists.';
}
.
➤ Save the create_directory.php file.
➤ Run the script by accessing it from your web browser or using the command line. If you are using the command line, navigate to the root directory of your Magento 2 installation and execute the following command:
php create_directory.php
The script will check if the directory with the given name ('custom_directory' in the example) already exists. If it doesn't exist, it will create the directory in the root directory of your Magento 2 installation.
Please note that this code snippet uses the Magento Object Manager to create the directory, but it's generally recommended to use Dependency Injection instead of directly using the Object Manager for better code architecture and maintainability. However, for a quick script like this, it should work fine. In a production environment or when writing more complex code, prefer using Dependency Injection.