2011-08-23 29 views
3

我有這個PHP腳本運行,允許用戶下載一個zip文件中的圖像文件夾,這意味着創建zip文件並將其發送給用戶,然後從服務器上刪除它。它工作正常,但有時它不會刪除zip。有任何想法嗎?PHP腳本發送zip文件,並在不工作後刪除

$filename_no_ext=$_GET['zip']; 

    // we deliver a zip file 
    header("Content-Type: archive/zip"); 

    // filename for the browser to save the zip file 
    header("Content-Disposition: attachment; filename=$filename_no_ext".".zip"); 

    // get a tmp name for the .zip 
    $tmp_zip = tempnam ("tmp", "tempname") . ".zip"; 

    // zip the stuff (dir and all in there) into the tmp_zip file 
    `zip -r $tmp_zip $filename_no_ext`; 

    // calc the length of the zip. it is needed for the progress bar of the browser 
    $filesize = filesize($tmp_zip); 

    header("Content-Length: $filesize"); 

    // deliver the zip file 
    $fp = fopen("$tmp_zip","r"); 
    echo fpassthru($fp); 
    fclose($fp); 

    // clean up the tmp zip file 
    //`rm $tmp_zip `; 
    unlink($tmp_zip); 

    //If user aborts check they have and then clean up the zip 
    ignore_user_abort(true); 

    echo "\n"; 
    if (connection_status()!=0){ 
     unlink($tmp_zip); 
    } 

    if (connection_aborted()) { 
     unlink($tmp_zip); 
    } 

任何幫助將是偉大的。

+0

你可能想使用php zip類而不是Unix命令'zip',少跨平臺http://www.php.net/manual/en/book.zip.php –

回答

0

我相信這發生在連接被主機「強制」中斷時發生。該腳本沒有完成解析,因此unlink()不會發生。我以前遇到過這個問題,所以你不能依靠腳本來刪除文件。

您有幾種解決方案。 你可以設置一個數據庫並保存下載信息,並做一個cron任務來刪除臨時壓縮文件。

您也可以製作一個cron,並檢查filemtime()並刪除如果超過1天。

最後一個選項是我的方法,但我對它做了一些小的調整,並以另一個用戶無法使用相同下載鏈接的方式進行了一些下載會話。

您可以將unlink()與cron任務結合使用。

+0

你的意思是說腳本在超過php.ini允許的最大持續時間後被中斷? –

+0

這是一個可能的問題,因爲我從來沒有想過爲什麼有時腳本有時不會100%執行。 –