PHP calls the command line of Linux to execute the file compression command

  • 2020-05-27 04:37:57
  • OfStack

A few days ago, I needed to package three txt files into *.zip down to local......
At the beginning, like ordinary youth 1, I thought of using PHP built-in ZipArchive. The code should look like this:
 
/* Split into 3 a txt file   , respectively, wow_1.txt wow_2.txt  and  wow_3.txt*/ 
$zip=new ZipArchive(); 
$zipfile='./Exl_file/wow.zip'; 
if($zip->open($zipfile,ZIPARCHIVE::CREATE)===TRUE){ 
$zip->addFile('./Exl_file/wow_1.txt','wow_1.txt'); 
$zip->addFile('./Exl_file/wow_2.txt','wow_2.txt'); 
$zip->addFile('./Exl_file/wow_3.txt','wow_3.txt'); 
$zip->close(); 
// Delete the relevant file after downloading the output file  
}else{ 
echo "ZIP Generation failed! "; 
} 

However, the problem is that zip extension is not installed on the formal environment, ZipArchive is not available directly, and the code is definitely faster than installing an extension on top of it -- using PHP to call the command line of Linux, execute the compression command, OK, act now!
 
/* Split into 3 a txt file   , respectively, wow_1.txt wow_2.txt  and  wow_3.txt All in  Exl_file  directory */ 
$outputs=array(); 
/* with php the exec perform Linux The command   The string in parentheses is where you are Linux A command typed in a command window;  
 The first 2 A parameter is linux The array of results returned after executing the command;  
linux Execute each of the returns 1 The results are stored in the array in sequence  
 The first 3 Two parameters are the result, if the execution is successful, then Linux Returns the result value of 0 , if the execution fails, the result value is not 0 
*/ 
exec("zip ./Exl_file/wow.zip ./Exl_file/wow_1.txt ./Exl_file/wow_2.txt ./Exl_file/wow_3.txt",$outputs,$rc); 
if($rc!=0){ 
foreach ($outputs as $ko=>$vo){ 
echo "$vo<br/>"; 
} 
}else{ 
$zipfile='./Exl_file/wow.zip'; 
// Delete the relevant file after the file is downloaded and output  
} 
} 

You can put if($rc! =0) change to if(1==1) to view the resulting lines returned by Linux execution, as shown below:
 
adding: Exl_file/wow_1.txt (deflated 96%) 
adding: Exl_file/wow_2.txt (deflated 97%) 
adding: Exl_file/wow_3.txt (deflated 97%) 

You can see that all the information returned from the execution was entered into the $outputs array, and the *.zip file was generated successfully.

Related articles: