How to rename file programmatically Magento 2?

You can rename the file names in Magento by providing the source path and destination path.

I have tested the given functionality to rename the file names under the pub directory. You can do it for outside pub directory but you need to change __construct() method $this->directory argument value.

$this->directory = $filesystem->getDirectoryWrite(DirectoryList::PUB);

I have explicitly given PUB directory so it will be renamed the file inside the pub directory only.

Let’s say we have to rename the XML file sitemap.xml from the path /pub/media/sitemap/sitemap.xml to other file names.

Target Path: media/sitemap/sitemap.xml
Resource Path: media/sitemap/demo.xml

Class Magento\Framework\Filesystem\Directory\Write having  renameFile()  that method will be used to rename file names.

renameFile() contains the First argument as $path and the Second argument is the $newPath.

I have created a sample Model class to rename the filename,



namespace Rbj\Blog\Model;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Directory\Write;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;

class RenameFile
    private Filesystem $filesystem;

    /** @var Write */
    private $directory;

    public function __construct(
        Filesystem $filesystem,
    ) {
        $this->filesystem = $filesystem;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::PUB);

    public function renameFile()
        $path = 'media/sitemap/sitemap.xml';
        $destination = 'media/sitemap/demo.xml';

        try {
            $this->directory->renameFile($path, $destination);
        } catch (\Exception $e) {
            throw new LocalizedException(
                __('Something went wrong while rename the file.'),

Use the above class and you will be able to successfully rename any files.