How to copy file and create folders if not exists

Hello folks, today, I come with the scenario, where I have to copy a bunch of files to new path from existing path. I have almost 250 files which are required to move with the same folder structure and I felt too lazy to copy and paste files by creating folders with the names. Rather I have path of those files which I have move.

I came up with a code snippet which copy your files from source to destination by creating folder structure too.

How to copy file and create folders if not exists

<?php

$allFiles = array(
'uploads/2012/product/vendors/keyboard.png',
'uploads/2014/product/vendors/sub/mouse-2.png',
'uploads/2014/product/vendors/mouse-1.png',
'uploads/2015/product/vendors/primary.png',
'uploads/2015/product/vendors/sub/seconday.png',
);

$sourcebase = 'codeigniter/';
$destbase = 'newpath/';

foreach($allFiles as $filepaths)
{
  
  if(file_exists($sourcebase.$filepaths))
  {	
    /** This code check and create the directory structure exists or not.
     * If not exists then create
     */
    $path = pathinfo($destbase.$filepaths);
    if (!file_exists($path['dirname'])) {
      mkdir($path['dirname'], 0777, true);
    }
    
    if(copy($sourcebase.$filepaths, $destbase.$filepaths))
    {
      print_r("=> Copy success");
    }
    else
    {
      print_r("=> Copy failed");
    }
  }
  else
  {
    print_r("=> source file not exists");
  }
}

?>

The code will create folder structure if not exists, then copy the file from source to destination.

Enjoy Coding!