php 打包tar.gz

    /**
     * author liuxiaodong
     * date 2019/3/6 09:48
     * @param $data array  imgs
     * @param $name
     * @return array
     * @throws Exception
     */
    public function createTarGz( $data, $name )
    {
        $tmp    = SITE_PATH . '/uploads/tar/' . date( 'dmy' ) . '/';
        if( !is_dir( $tmp ) )
            if( !mkdir( $tmp, 0777, true ) )
                throw new Exception( '创建目录失败,请检查' );

        $tmpTar     = $tmp . $name . '.tar';
        $retfile    = $tmp . $name . '.tar.gz';
        @unlink( $retfile );

        try{
            $phar   = new \PharData( $tmpTar );
            $phar->addEmptyDir( 'ad' );//业务要求建个ad目录;可以忽略该步
            foreach( $data as $k=> $path ) {
                $path   = realpath( $path );
                $ext    = substr( $path, strpos( $path, '.' ) );
                $phar->addFile( $path, 'ad/' . $k . $ext );//ad 可以忽略
            }
            $phar->compress( \Phar::GZ );
        }catch ( Exception $e ) {
            throw new Exception( '压缩包生成失败:' . $e->getMessage() );
        }

        if( !file_exists( $retfile ) )
            throw new Exception( '压缩包生成失败' );
        unlink( $tmpTar );

        $url        = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . dirname( $_SERVER['SCRIPT_NAME'] );
        return [
            'path'  => str_replace( SITE_PATH, '.', $retfile ),
            'md5'   => md5_file( $retfile ),
            'url'   => str_replace( SITE_PATH, $url, $retfile ),
        ];
    }

 

posted @ 2019-03-06 10:43  栋的博客  阅读(1431)  评论(0编辑  收藏  举报
深入理解php php扩展开发 docker mongodb