Search code examples
phpunzip

file_put_contents in to new directory


I have the following code, which as you can see i use to create a new directory then unzip a file.

<?php

function unzip_to_s3() { 

// Set temp path
$temp_path = 'wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/tmp/';

// Get filename from Zip file
$zip_file = 'archive.zip';

// Create full Zip file path
$zip_file_path = $temp_path.$zip_file;

// Generate unique name for temp sub_folder for unzipped files
$temp_unzip_folder = uniqid('temp_TMS_', true);

// Create full temp sub_folder path
$temp_unzip_path = $temp_path.$temp_unzip_folder;

// Make the new temp sub_folder for unzipped files
if (!mkdir($temp_unzip_path, '0755', true)) {
    die('Error: Could not create path: '.$temp_unzip_path);
}

// Unzip files to temp unzip folder, ignoring anything that is not a .mp3 extension
$zip = new ZipArchive();
$filename = $zip_file_path;

if ($zip->open($filename)!==TRUE) {
   exit("cannot open <$filename>\n");
}

for ($i=0; $i<$zip->numFiles;$i++) {
   $info = $zip->statIndex($i);
   $file = pathinfo($info['name']);
   if(strtolower($file['extension']) == "mp3") {
        file_put_contents(basename($info['name']), $zip->getFromIndex($i));
   } else {
   $zip->deleteIndex($i);
   }
}
$zip->close();

}

unzip_to_s3();

?>

The unzip code was courtesy of @TotalWipeOut from one of my other posts. It currently unzips just mp3 files to my base directory, but i want to put them in my newly created folder.

I'm very new to PHP so have been trying my best with this, but i can't figure out how to change the file_put_contents(basename($info['name']), $zip->getFromIndex($i)); line to get it to put the files in my new folder?


Solution

  • As Marc B. mentioned you need to include the path to the directory you are putting the file in.

    using your code:

    file_put_contents($temp_unzip_path."/".basename($info['name']), $zip->getFromIndex($i));
    

    I would also suggest reading a little more about the basics of PHP.