2015-10-30 50 views
0

我对PHP很陌生,我只是制作了我的第一个脚本,该脚本工作正常,但缺少最终的触摸。 脚本将包含php的文件夹中的所有文件压缩并创建可下载的压缩文件。 下面的代码将文件压缩到一个文件夹中并给出存档文件夹的名称

<?php 

$zipname = 'test.zip'; 
$zip = new ZipArchive; 
$zip->open('D://mypath//zip//$zipname', ZipArchive::CREATE); 
if ($dir_handle = opendir('./')) { 
    while (false !== ($entry = readdir($dir_handle))) { 
    if ($entry != "." && $entry != ".." && !strstr($entry,'.php') && !strstr($entry,'.zip')) { 
     $zip->addFile($entry); 
    } 
    } 
    closedir($dir_handle); 
} 
else { 
    die('file not found'); 
} 

$zip->close(); 

header('Content-Type: application/zip'); 
header("Content-Disposition: attachment; filename=$zipname"); 
header('Content-Length: ' . filesize($zipname)); 
header("Location: $zipname"); 

?> 

我想达成什么是有$ zipname =“的folder.zip的名字” 所以,如果PHP是内部“/ mypath中/ blablabla /”我希望我的zip $ zipname成为“blablabla.zip”

任何帮助将不胜感激!

编辑: 这里的工作代码:

<?php 
$zipname = getcwd(); 
$zipname = substr($zipname,strrpos($zipname,'\\')+1); 
$zipname = $zipname.'.zip'; 
$zip = new ZipArchive; 
$zip->open('D:/inetpub/webs/mydomaincom/zip/'.basename($zipname).'', ZipArchive::CREATE); 
if ($dir_handle = opendir('./')) { 
    while (false !== ($entry = readdir($dir_handle))) { 
if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) { 
    $zip->addFile($entry); 
} 
} 
closedir($dir_handle); 
} 
else { 
die('file not found'); 
} 

$zip->close(); 

header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename="'.basename($zipname).'"'); 
header('Content-Length: ' . filesize($zipname)); 
header('Location: /zip/'.$zipname); 
?> 
+0

你找不到一个函数来获取路径? –

回答

0

你可以使用GETCWD():

http://php.net/manual/fr/function.getcwd.php

$zipname = getcwd(); 

这将返回当前文件夹的路径,然后您只需散列结果即可获得文件夹的名称:

// We remove all the uneeded part of the path 
$zipname = substr($zipname,strrpos($zipname,'\\')+1); 

//Then we add .zip to the result : 
$zipname = $zipname.'.zip'; 

这应该可以做到。

如果你也想使用父文件夹的名称:

$zipname = getcwd(); 

// We remove the uneeded part of the path 
$parentFolderPath = substr($zipname, 0,strrpos($zipname,'\\')); 
$parentFolder = substr($parentFolderPath, strrpos($parentFolderPath,'\\')+1); 

//Keep current folder name 
$currentFolder = substr($zipname,strrpos($zipname,'\\')+1); 

//Join both 
$zipname = $parentFolder.'_'.$currentFolder; 

//Then we add .zip to the result : 
$zipname = $zipname.'.zip'; 
+0

它实际上做了诡计! – brunogermain

+0

没有问题,不要忘记把你的问题解决:) – Nirnae

+0

其实它还没有解决。我无法正确下载文件(下载的档案为空,但我可以看到档案正在服务器上正确创建)。我认为这是因为档案被保存到一个不同的目录,我不是很好的头文件... – brunogermain

0

而是与header()重定向的,你可以使用readfile()

header('Content-Disposition: attachment; filename="'.basename($zipname).'"'); 
readfile($zipname); 

随着basename()只有最后一部分是向用户显示,并且与readfile()一样,您正在发放实际文件,无论它在哪里。

+0

readfile($ zipname)指向我使用正确的名称下载一个空存档。请注意,zip压缩文件不是在我压缩的同一文件夹中创建的,它实际上位于/ zip /文件夹中。我如何指出这一点? – brunogermain

相关问题