Search code examples
phpfile-put-contents

Copy file into new directory (PHP)


I asked a similar question previously, but didn't know how to quite ask before. Below I created a new directory based on the username I grabbed from a signup form. I just need the inclusion of the template file copied over to the new directory that was just made. The outcome I'm getting is an inclusion of the file in the directory that's up one level. The new directory is created with the username but doesn't contain the template file in its directory. I spent hours on this so I wouldn't have to bother you guys again. What am I doing wrong?

 $folder = DIRECTORY_SEPARATOR; // adds the forward slash
   $name = $user->username;   // included from a login script I purchased 
   $thisdir = "../associate"; // desired directory
   $folderPath = $thisdir . $folder . $name;
   $file = copy('../associate/joshua/career.php', $folderPath.'.php'); // copy this file into new directory
        if(!file_exists($folderPath)){
            mkdir($folderPath);
            chmod($folderPath,0777);
        }

     file_put_contents(realpath($folderPath) .'/'. $folderPath, $file);

    });

Solution

  • If I understand you well, you want to copy career.php template from /associates/ folder to /associates/username/ folder

       $rootfolder = $_SERVER['DOCUMENT_ROOT'];
       $name = $user->username;  
       $thisdir = "/associate/";
       $folderPath = $rootfolder.$thisdir.$name."/"; // desired directory
    
    if(!is_dir($folderPath)){
            mkdir($folderPath, 0777, true);
        }
    $currentfile = $rootfolder.$thisdir.'joshua/career.php';
        $destination = $folderPath.'career.php';
      copy($currentfile, $destination); // copy this file into new directory