使用PHP+TAR提取文件夹


Using PHP + TAR to extract a folder

我想自动将最新的WordPress版本下载到Web服务器的根文件夹中。这是我到目前为止的代码:

<?php
$fp = fopen (dirname(__FILE__) . '/wp.tar.gz', 'w+');
$ch = curl_init('http://wordpress.org/latest.tar.gz');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
exec('tar -zxvf wp.tar.gz wordpress');
unlink('wp.tar.gz');
?>

问题是,WordPress的tar文件包含一个目录/WordPress,其中包含所有文件,所以在运行这个PHP文件后,我现在有一个/WordPress目录,其中包含文件,但我希望它位于/(PHP文件运行的位置),而不是/WordPress中的所有内容。还是应该使用"mv"命令将所有内容从/wordpress移动到/?

感谢

如果您使用的是GNU或BSD tar:的新版本

exec('tar -zxvf --strip-components=1 wp.tar.gz wordpress');

顺便说一句,如果不需要提取文件的列表,则不需要v选项。

另请参阅:如何从tarball中提取特定目录?并剥离一个前导目录?

Why dont you use this : 
http://wordpress.org/latest.zip
Then your code would look like:
<?php
$filename = "http://wordpress.org/latest.zip";
$contents = file_get_contents($filename);
$latestzip_file = 'latest.zip';
$fh = fopen($latestzip_file, 'w') or die("can't open file");
fwrite($fh, $contents);
fclose($fh);
$zip = new ZipArchive;
$res = $zip->open($latestzip_file);
if($res === TRUE)
{
      $zip->extractTo(dirname(__FILE__));       // Extract to the main directory //
  $zip->close();
      unlink($latestzip_file);
    }
?>

尝试添加--strip=1 opt

  tar xvzf wp.tar.gz --strip=1