項目涉及文檔處理,用戶上傳的包括 zip 和 rar 壓縮包,需要先將壓縮包解壓后再作處理。對于 zip 壓縮包,由于 php 自帶 zip 擴展,可以直接解壓。
解壓zip壓縮包:
1
2
3
4
5
6
7
8
|
$file = "/opt/data/upload/testfile.zip" ; $outPath = "/opt/data/upload/testfile" ; $zip = new ZipArchive(); $openRes = $zip ->open( $file ); if ( $openRes === TRUE) { $zip ->extractTo( $outPath ); $zip ->close(); } |
對于 rar 壓縮包,需要先為 php 安裝 rar 擴展。
安裝rar擴展:
1
2
3
4
5
6
7
8
9
10
11
|
wget http: //pecl.php.net/get/rar-4.0.0.tgz gunzip rar-4.0.0.tgz tar -xvf rar-4.0.0.tar cd rar-4.0.0 phpize ./configure && make && make install # 報錯 configure: error: Cannot find php-config. Please use --with-php-config=PATH # 運行./configure 時指定php-config路徑即可 ./configure --with-php-config=/usr/local/php/bin/php-config make && make install |
配置rar擴展:
1
2
|
# 新建 /usr/local/php/conf.d/rar.ini,內容 extension=rar.so |
重啟 php-fpm
,看一下 phpinfo() ;
可以看到已經成功安裝了 rar ,可以來測試一下解壓 rar 文件。
解壓RAR壓縮包:
1
2
3
4
5
6
7
8
9
10
|
$file = "/opt/data/upload/testfile.zip" ; $outPath = "/opt/data/upload/testfile" ; $rar_file = rar_open( $file ); if ( $rar_file ) { $entries = rar_list( $rar_file ); foreach ( $entries as $entry ) { $entry ->extract( $outPath ); } rar_close( $rar_file ); } |
這樣就搞定用戶上傳的壓縮包解壓的問題了。
總結
以上所述是小編給大家介紹的php解壓縮zip和rar壓縮包文件的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
原文鏈接:https://beltxman.com/archives/2531.html