• 首页
  • css3教程
  • html5教程
  • jQuery手册
  • php7教程
  • MySQL手册
  • apache手册
  • 位置: php7教程 -> PECL扩展库

    Rar(压缩)

    此 PECL 扩展未与 PHP 捆绑。 还可以使用PECL安装程序安装Rar扩展,使用以下命令:pecl -v install rar。您始终可以下载tar.gz包并手动安装Rar:

    gunzip rar-xxx.tgz
    tar -xvf rar-xxx.tar
    cd rar-xxx
    phpize
    ./configure && make && make install
    

    Windows用户将在php.ini中启用php_rar.dll以使用这些函数

    Windows users download php_rar.dll at http://pecl.php.net/package/rar
    0. click the DLL link for Windows
    1. download php_rar.dll for your php version
    2. copy php_rar.dll to the "ext" folder
    3. append the following directive to the [php] section of your working php.ini, you can search "extension=" and append it to the last extension directive.
    extension=php_rar.dll
    4. restart your web server and enjoy.
    
    After installing RAR 2.0.0 extension in PHP 5.3.3 on OpenSUSE 11.3 using pecl command line, i had to enable it by creating a file named
    /etc/php5/conf.d/rar.ini
    which contains this line
    extension=rar.so
    

    Example #1 On-the-fly decompression

    <?php
    if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
        die("Index unspecified or non-numeric");
    $index = (int) $_GET["i"];
        
    $arch = RarArchive::open("example.rar");
    if ($arch === FALSE)
        die("Cannot open example.rar");
    $entries = $arch->getEntries();
    if ($entries === FALSE)
        die("Cannot retrieve entries");
    if (!array_key_exists($index, $entries))
        die("No such index: $index");
    $orfilename = $entries[$index]->getName(); //UTF-8 encoded
    $filesize = $entries[$index]->getUnpackedSize();
    /* you could check HTTP_IF_MODIFIED_SINCE here and compare with
     * $entries[$index]->getFileTime(). You could also send a
     * "Last modified" header */
    $fp = $entries[$index]->getStream();
    if ($fp === FALSE)
        die("Cannot open file with index $index insided the archive.");
    $arch->close(); //no longer needed; stream is independent
    function detectUserAgent() {
        if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
            return "Other";
        
        $uas = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match("@Opera/@", $uas))
            return "Opera";
        if (preg_match("@Firefox/@", $uas))
            return "Firefox";
        if (preg_match("@Chrome/@", $uas))
            return "Chrome";
        if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
            if (((float)$matches[1]) >= 7.0)
                return "IE";
        }
        
        return "Other";
    }
    /*
     * We have 3 options:
     * - For FF and Opera, which support RFC 2231, use that format.
     * - For IE and Chrome, use attwithfnrawpctenclong
     *   (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
     * - For the others, convert to ISO-8859-1, if possible
     */
    $formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
    $formatDef = 'Content-Disposition: attachment; filename="%s"';
    switch (detectUserAgent()) {
        case "Opera":
        case "Firefox":
            $orfilename = rawurlencode($orfilename);
            $format = $formatRFC2231;
            break;
        case "IE":
        case "Chrome":
            $orfilename = rawurlencode($orfilename);
            $format = $formatDef;
            break;
        default:
            if (function_exists('iconv'))
                $orfilename =
                    @iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
            $format = $formatDef;
    }
    header(sprintf($format, $orfilename));
    //cannot send error messages from now on (headers already sent)
    //replace by real content type, perhaps infering from the file extension
    $contentType = "application/octet-stream";
    header("Content-Type: $contentType");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: $filesize");
    if ($_SERVER['REQUEST_METHOD'] == "HEAD")
        die();
        
    while (!feof($fp)) {
        $s = @fread($fp, 8192);
        if ($s === false)
            break; //useless to send error messages
      
        echo $s;
    }
    ?>
    

    This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

    Example #2 RAR extension filesystem extraction example

    <?php
    $rar_file = rar_open('example.rar') or die("Can't open Rar archive");
    $entries = rar_list($rar_file);
    foreach ($entries as $entry) {
        echo 'Filename: ' . $entry->getName() . "\n";
        echo 'Packed size: ' . $entry->getPackedSize() . "\n";
        echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
        $entry->extract('/dir/extract/to/');
    }
    rar_close($rar_file);
    ?>
    

    This example opens a RAR file archive and extracts each entry to the specified directory.

    A veeery simple function to RAR files, I'm not proud of it.
    Since there's no way to create RAR files in PHP (due to licensing, patents or whatever), I'm taking some advantage from the command-line RARing tool that comes with WinRAR (in the WinRAR program files named "rar.exe").
    <?php
    function RARFiles($Output='output.rar',$Files=array()) {
     $Data='';
     for($i=0;$i<count($Files);$i++)
      $Data.="\"{$Files[$i]}\" ";
     exec("rar.exe a \"{$Output}\" {$Data}");
    }
    $Files=array('file1.ext','file2.ext','file3.ext');
    RARFiles('asdf.rar',$Files);
    // asdf.rar created.
    ?>
    There's no error checking, so make sure you check that your expected RAR file exists before doing anything with it.
    Hopefully one day, PHP will be able to be allowed to create RAR files.