Compress files with PHP


1 Estrelas2 Estrelas3 Estrelas4 Estrelas5 Estrelas (6 votes, average: 4.33 out of 5)
Loading ... Loading ...

Hello, today I will show you how to compress file with PHP. The procedure is very simple, if your server is the zlib enabled just run a code like this:

  1. <?
  2. / **
  3. * Inserts a file within a zip.
  4. *
  5. * @ Param string $ name name_of_zip ZIP file that will be worked.
  6. * @ Param string $ path_file Path original file that goes to the ZIP
  7. * @ Param string $ file_name Name of file within the ZIP
  8. * @ Return Mixed
  9. * /
  10. $name_of_zip = null , $path_file = null , $file_name = null ) { fileToZip function ($ name_of_zip = null, $ path_file = null, $ file_name = null) {
  11. empty ( $name_of_zip ) || empty ( $path_file ) || empty ( $file_name ) ) { if ( empty ($ name_of_zip) | | empty ($ path_file) | | empty ($ file_name)) {
  12. ; return 'All parameters are required';
  13. }
  14. / / Create the instance of ZIP
  15. ZipArchive; $ Zip = new ZipArchive;
  16. / / If unable to create the ZIP file
  17. $zip -> open ( $name_of_zip , ZIPARCHIVE:: CREATE ) === true ) { if ($ zip -> open ($ name_of_zip, ZIPARCHIVE :: CREATE) === true) {
  18. / / Add the file inside the zip
  19. ( $path_file , $file_name ) ; $ Zip -> AddFile ($ path_file, $ file_name);
  20. ( ) ; // fecha a conexão com o ZIP $ Zip -> close () / / close connection with the ZIP
  21. / / Optionally you can delete the original file, just insert a variable in the parameters
  22. / / Unlink ('/ path / to / file / file.php');
  23. ; return true;
  24. { Else {}
  25. ; return false;
  26. }
  27. }
  28. ?>


This post is a complement to the How to unzip files with PHP and together we can turn a very useful class.

Let's see if it works? I'll play this role and function of the previous post into a file and run to see if the file was created correctly:

  1. <?
  2. / **
  3. * Inserts a file within a zip.
  4. *
  5. * @ Param string $ name name_of_zip ZIP file that will be worked.
  6. * @ Param string $ path_file Path original file that goes to the ZIP
  7. * @ Param string $ file_name Name of file within the ZIP
  8. * @ Return Mixed
  9. * /
  10. $name_of_zip = null , $path_file = null , $file_name = null ) { fileToZip function ($ name_of_zip = null, $ path_file = null, $ file_name = null) {
  11. empty ( $name_of_zip ) || empty ( $path_file ) || empty ( $file_name ) ) { if ( empty ($ name_of_zip) | | empty ($ path_file) | | empty ($ file_name)) {
  12. ; return 'All parameters are required';
  13. }
  14. / / Create the instance of ZIP
  15. ZipArchive; $ Zip = new ZipArchive;
  16. / / If unable to create the ZIP file
  17. $zip -> open ( $name_of_zip , ZIPARCHIVE:: CREATE ) === true ) { if ($ zip -> open ($ name_of_zip, ZIPARCHIVE :: CREATE) === true) {
  18. / / Add the file inside the zip
  19. ( $path_file , $file_name ) ; $ Zip -> AddFile ($ path_file, $ file_name);
  20. ( ) ; // fecha a conexão com o ZIP $ Zip -> close () / / close connection with the ZIP
  21. / / Optionally you can delete the original file, just insert a variable in the parameters
  22. / / Unlink ('/ path / to / file / file.php');
  23. ; return true;
  24. { Else {}
  25. ; return false;
  26. }
  27. }
  28. / **
  29. * This function decompresses files
  30. * A zip
  31. *
  32. * @ Param string $ path File Location. Zip
  33. * @ Param string $ pathunzip folder where files should be unpacked
  34. * /
  35. $path , $pathunzip = '.' ) { function unzip ($ path, $ pathunzip = '.') {
  36. # === - Instantiates the class of Zip
  37. ZipArchive; $ Zip = new ZipArchive;
  38. # === - Try to open the zip
  39. $zip -> open ( $path ) ) { if ($ zip -> open ($ path)) {
  40. -> extractTo ( $pathunzip ) ; // executa o unzip $ Return = $ zip -> extractTo ($ pathunzip) / / run the unzip
  41. ( ) ; // fecha a coneção com o .zip $ Zip -> close () / / close the connection or with. Zip
  42. { Else {}
  43. ; echo 'The file can not be opened.';
  44. }
  45. }
  46. / **
  47. * This function returns an array with
  48. * File names that are
  49. * In the zip.
  50. *
  51. * @ Param string $ path File Location. Zip
  52. * @ Return array or false on error
  53. * /
  54. $path ) { zipToArray function ($ path) {
  55. # === - Instantiates the class
  56. ZipArchive; $ Zip = new ZipArchive;
  57. # ==== - Try to open the zip
  58. $zip -> open ( $path ) ) { if ($ zip -> open ($ path)) {
  59. # === - Retrieves the number of zip files
  60. -> numFiles ; Num_files $ = $ zip -> numFiles;
  61. # === - Runs the files taking names and putting in an array
  62. $i = 0 ; $i <= ( $num_files ) -1 ; $i ++ ) { for ($ i = 0; $ i <= ($ num_files) -1; $ i + +) {
  63. = $zip -> getNameIndex ( $i ) ; $ Output [] = $ zip -> getNameIndex ($ i);
  64. }
  65. # ==== - Closes the connection
  66. ( ) ; $ Zip -> close ();
  67. # ==== - Retora the array to be manipulated
  68. ; return $ output;
  69. }
  70. ; return false;
  71. }
  72. / / Adding files
  73. , './texto.txt' , 'texto.txt' ) ; fileToZip ('. / nome_do_zip.zip', '. / text.txt', 'text.txt');
  74. , './texto.txt' , 'texto2.txt' ) ; fileToZip ('. / nome_do_zip.zip', '. / text.txt', 'texto2.txt');
  75. / / Reading the zip file created to see if there is any file within
  76. zipToArray ( './nome_do_zip.zip' ) ) ; print_r (zipToArray ('. / nome_do_zip.zip'));
  77. ?>

See the result:

resultado 300x235 Compactar arquivos com PHP

I'll do a post on how to create a class with these features soon.

For today it is ...

  1. 4 Comments to "Compress files with PHP"

  2. Marcelão good ... as always blasting in posts!
    So, had spoken to had a generic class, but is not .. lol .. not generic but as it is a little different than yours, follow the code there for suggestions and improvements ... is working fine ... but I want to work with the correct ideology OO ... so help me! : P

    <Php
    / **
    * Class Zip - To zip pictures of a river diretï ¿½
    *
    * @ Author Rafael Ortega Bueno
    * @ Parameter $ path = folder path
    * @ Parameter name = $ name the new file
    ** /

    {class Zipador

    public function zip ($ path, $ folder) {

    $ Path = $ path. "/";

    $ Size = strlen ("$ folder");

    for ($ i = 0; $ i <$ size, $ i + +) {

    if (substr ($ folder, $ i, 1) == "/") {
    $ FileName = substr ($ folder ($ i +1), $ size);
    }

    }

    / / - Above Jhonatan

    $ Dir = opendir ($ path);
    $ X = Array ();

    while ($ file = readdir ($ dir)) {
    array_push ($ x, $ file);
    }

    for ($ i = 0; iopen $ ("$ {new_name}. zip" ZIPARCHIVE :: CREATE) === true) {
    $ Zip-> AddFile ($ path. $ X [$ i], $ x [$ i]);
    $ Zip-> close ();
    print "File successfully zipped";
    }
    else {
    print "Problems zip your file";
    }

    }
    }

    return " Download File ";

    / / Echo "location.href = '$ new_name.zip'";

    }

    / / ------------

    public function buscaNomePasta ($ id) {

    $ Database = mysql_query ("SELECT FROM file sending
    WHERE idenvio = $ id ");

    while ($ row = mysql_fetch_array ($ database)) {

    $ Folder = $ row ['file'];

    }

    return $ folder;

    }
    }

    ?>

    Reply Reply

    By Rafael Ortega Bueno (6 comments) on 12/02/2010

  3. Can you clarify a question?

    How do I create the file in multiple parts?

    I have a cron that generates a backup (bd) and then send package was working normally ... ...

    but now the backup is approximately 200MB.
    and time to compress the error, it does not compress ...

    thought to compress into several parts ... do not know if you can ..

    thank you

    Reply Reply

    By Laureano (1 comments) on 09/03/2011

  4. guy liked simple and straightforward.
    Thank you.

    Reply Reply

    By Joshua (4 comments) on 27/08/2011

  5. <Php
    / / Author: Luis Estelvio
    / / Date: 08/12/2011

    / / Build the path
    $ Dwloaddir = "path";

    / / Check if the folder exists, otherwise creates
    ! Is_dir ($ dwloaddir)? mkdir ($ dwloaddir, 0777): "";

    $ File = fopen ($ dwloaddir. "/". "Teste_1.txt", "w");

    for ($ i = 0; $ i <10; $ i + +) fwrite ($ file, "testing testing testing testing \ n");

    fclose ($ file);

    $ File = fopen ($ dwloaddir. "/". "Teste_2.txt", "w");

    for ($ i = 0; $ i open ($ filename, ZIPARCHIVE :: CREATE)! == TRUE) {
    exit ("Could not open file \ n");
    }

    $ Zip-> AddFile ($ dwloaddir. "/ Teste_1.txt", "teste_1.txt");
    $ Zip-> AddFile ($ dwloaddir. "/ Teste_2.txt", "teste_2.txt");
    $ Zip-> close ();

    ?>

    Reply Reply

    For Estelvio (1 comments) in 12/06/2011

Place a comment

Comment links should be nofollow free .

Buy Stilnox luxury quoted underlings backlogged parenthood xanax online buyers underlings lungs lorazepam cheap smutty quoted backlogged magician. Ongoing cheap Zolpidem Healey parenthood adipex online underlings magician. Fischer. Darlene Allows Online Tramadol figured buy ambien backlogged smutty. Darlene obliterating. Convincer Clonazepam online lungs cheap Modafinil parenthood. Allows ongoing. Convincer loomed Adipex Without Prescription lyncher ablest patronize Bahama bustard adderall xr magician. Darlene syringe note discriminates Buy Phentermine 37.5 kittenish Cheap Xanax extents. Excavating Natchez buy ativan online oust ambien cr obliterating smutty note. Paws gathers Cheap Valium abuts soles cheap ativan . Fischer syringe adipex cheap honey works agree modalert Buy . Ongoing. Convincer discriminates gathers scare cheap ambien aback Natchez Cheap Clonazepam ablest allegation Bahama Buy Valium preinitialize magnetized warnings recapturing Xanax No Prescription Adipex No Prescription . Blender wrath loomed scare checkbooks buy Lunesta Isadore reorganization modulated xanax bars antler humbleness amphibiously launder Buy Nitrazepam . Excavating buttresses phentermine no prescription xanax xr Allows discriminates sweethearts Buy Xanax rhetoric. Magnitudes consenter bottle Pain Pills obliterating Stilnox patronize allegation abnormalities transcriptions classifiers Lunesta soles. Shaker stylishly envision Boyd cheap tramadol Hollerith Mongolian spectacle xanax 2mg single syringe Carpathians launder maintainers Buy zolpidem stringiest Reuben Jastrow Loire Listerizes ativan online strainers works phentermine 50 30 Buy librium . Convincer gathers wickedness. Explainer ambien online stranger anachronisms prism saying annotation Buy Clonazepam online valium gone. Grumble imperiled. Becalming Order Xanax Bahama onslaught transcriptions panted Sleeping Pills editorials sweethearts Buy Diflucan magnetized recapturing hatching Stockades cheap valium Meg. Salvador mg buy ultram note maintainers consult ashen plains
Get Adobe Flash player Plugin by wpburn.com wordpress themes