Search code examples
phpopensslunzipphp-5.6

Copy from one folder, Decrypt then unzip using PHP


$dir = "/var/www/html/test";
$localDir  = "/home/hell/local/db";
$pass = "123456789";
$method = "aes-256-cbc";


$out = "/home/hell/Downloads/db;


$files = scandir($dir);
if (!empty($files)) {
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            if (substr($file, 0, 11)== date('d-M-Y')) {


                 // code...

                copy(".$dir."/".$file.",".$localDir."/".$file");

                $zipName = basename($localDir."/".$file,".aes").".zip";

                $exec = "openssl ".$method." -d -salt -in ".$localDir."/".$file." -out ".$out.$zipName. " -k ".$pass;




            }

        }
    }
}

My aim is to copy a .aes file from /var/www/html/test to /home/hell/local/db then decrypt it, then unzip it and delete the copied file and its zip. So far this is what i manage and the code runs with out errors but doesn't produce the archived file to unzip. it doesnt produce the file to unzip.


Solution

  • //function to drop database
    system("mysql -h".$servername ." -u" .$username ." -p" .$password ." -e 'DROP DATABASE IF EXISTS $dbname'");
    
    
    //function to create database 
    system("mysql -h".$servername ." -u" .$username ." -p" .$password ." -e 'CREATE DATABASE $dbname'");
    
    $files = scandir($dir, SCANDIR_SORT_DESCENDING);
    //$files = "\.(aes|AES)$"
    $newest_file = $files[0];
    
    $oldPath = $dir."/".$newest_file;
    $newPath = $localDir."/".$newest_file."\n";
    
    shell_exec("cp ".$oldPath." ".$newPath);
    
    // copy('".$dir."/".$newest_file."','".$localDir."/".$newest_file."');
    $zipName = basename($localDir."/".$newest_file, ".aes");
    
    exec("openssl ".$method." -d -salt -in ".$localDir."/".$newest_file." -out ".$out.$zipName. " -k ".$pass);
    
    //print $zipName."\n";
    //print $out.$zipName."\n";
    $sqlName = basename($zipName, ".zip");
    
    system("unzip ".$out.$zipName." -d " .$localDir."/"); 
    
    print $localDir."/".$sqlName."\n";
    
    $sq12 = "mysql -h" .$servername ." -u" .$username ." -p" .$password ." " .$dbname ." < " .$localDir."/".$sqlName;
    
    if(exec($sq12)) {
    
        //unlink($out);
        exec("rm" .$localDir."*");
    }
    
    ?>
    

    You can never go wrong with exec() or system() function.