2012-07-09 74 views
0

我正在使用下面的簡單腳本通過php上傳zip文件,然後將其解壓縮到我的服務器上。PHP文件上傳然後顯示下載鏈接

該文件將是一個壓縮文件夾。上傳完成後,我想回顯一個指向新文件夾的鏈接。

因此,例如,如果我上傳包含名爲「bar」的文件夾的zip文件,在成功消息之後,我想回顯「http://foo.com/bar」。

任何幫助非常感謝。

<?php 
if($_FILES["zip_file"]["name"]) { 
$filename = $_FILES["zip_file"]["name"]; 
$source = $_FILES["zip_file"]["tmp_name"]; 
$type = $_FILES["zip_file"]["type"]; 

$name = explode(".", $filename); 
$accepted_types = array('application/zip', 'application/x-zip-compressed', 
'multipart/x-zip', 'application/x-compressed'); 
foreach($accepted_types as $mime_type) { 
    if($mime_type == $type) { 
     $okay = true; 
     break; 
    } 
} 

$continue = strtolower($name[1]) == 'zip' ? true : false; 
if(!$continue) { 
    $message = "The file you are trying to upload is not a .zip file. Please try again."; 
} 

$target_path = "/home/var/foo.com/".$filename; // change this to the correct  
site  path 
if(move_uploaded_file($source, $target_path)) { 
    $zip = new ZipArchive(); 
    $x = $zip->open($target_path); 
    if ($x === true) { 
     $zip->extractTo("/home/var/foo.com/"); // change this to the correct site path 
     $zip->close(); 

     unlink($target_path); 
    } 
    $message = "Your .zip file was uploaded and unpacked."; 
} else {  
    $message = "There was a problem with the upload. Please try again."; 
} 
} 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 
/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 
<?php if($message) echo "<p>$message</p>"; ?> 
<form enctype="multipart/form-data" method="post" action=""> 
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label> 
<br /> 
<input type="submit" name="submit" value="Upload" /> 
</form> 
</body> 
</html> 
+0

你的代碼似乎正確,寫得很好。你試圖解決的問題究竟是什麼?此代碼是否顯示任何錯誤? – akanevsky 2012-07-09 01:03:19

回答

0

接管一切看一眼,我會說

$message = "Your .zip file was uploaded and unpacked. <a href=\"http://domain.com".$filename."\">Files</a>"; 
從我收集關於你的腳本你告訴它直接上傳到域的服務器的目錄路徑

。將$filename作爲文件夾名追加到該路徑,以便相應地創建文件夾。從它硬編碼像你這樣的域到其他任何鏈接,然後將相同的文件名變量附加到它的末尾,以顯示剛剛上傳到的相同文件夾。

這只是我的總體猜測,儘管只是快速瀏覽一下。

0

從你的代碼的詳細資料,我會說,我可以給一些意見:

1)您應該使用的mkdir()創建在您的網站上載目錄的新目錄(我假設這是這種情況下的根源)。

2)在解壓縮之前,您不需要移動上傳的文件。只需將其解壓到新創建的目錄中即可。確保沒有另一個具有相同名稱的目錄。上傳的文件應該由PHP自動刪除,所以不需要取消鏈接。

3)中提到:

$name = explode(".", $filename); 

會發生什麼,如果文件名有超過一個點?你應該使用substr()和strrpos()來獲取最後一個點之後的所有東西。

4)上傳後,只需回顯路徑http://www.yoursite.com/newdir - 看不到問題。如果您可以更具體地瞭解您遇到的困難,請發表評論。