2016-04-20 71 views
2

我有HTML文件輸入並提交它與ajax,然後在php我做curl請求並上傳文件到另一臺服務器,當文件上傳時,我發送另一個ajax請求並獲取curl進度,並在html上顯示它,它目前工作,沒有問題。但是當我刷新頁面時,文件仍然上傳,curl請求未關閉,仍然在後臺運行,我想刷新頁面時,curl請求也關閉。刷新頁面時PHP curl請求不關閉

這是index.php文件

<!DOCTYPE html> 
<html> 
<head> 
<title>sad</title> 
</head> 
<body> 
<form action="up.php" method="post"> 
<input type="file" name='file'></input> 
<button type="submit">Upload</button> 
</form> 
<progress id="progress" value="0" max="100"></progress> 

<div id="myResultsDiv"></div> 


<script type="text/javascript" src="jquery-1.12.3.min.js"></script> 
<script type="text/javascript" src="jquery.form.min.js"></script> 

<script type="text/javascript"> 
var progressSetInterval = null;// Global 

    $(document).ready(function() { 
     var time = Date.now(); 
     // bind submit handler to form 
     $('form').on('submit', function(e) { 
      e.preventDefault(); // prevent native submit 
      $(this).ajaxSubmit({ 
       url: 'up.php?t=' + time, 
       target: '#myResultsDiv' 
      }); 

      progressSetInterval = setInterval(function(){ 
       $.ajax({ 
       type: "POST", 
       url: "progressFile_" + time + '.txt?t=' + Date.now(), 
       success: function(data){ 
        $('#progress').attr('value' , data); 
        if(data >= 100) { 
        clearInterval(progressSetInterval); 
        } 
       } 
      }); 
     }, 3000); 
     }); 
    }); 
</script> 
</body> 
</html> 

我的HTML代碼,並在我的PHP代碼up.php

<?php 
Class Upload { 
public $progressFile = ''; 

public function up($file) { 
    flush(); 
    $ch = curl_init(); 
    $localfile = $file['tmp_name']; 
    $path = 'ftp://dl.mywebsite.com/public_html/' . time() . '_' . $file['name']; 
    $fp = fopen($localfile, 'r'); 
    curl_setopt($ch, CURLOPT_URL, $path); 
    curl_setopt($ch, CURLOPT_USERPWD, 'username:password'); 
    curl_setopt($ch, CURLOPT_UPLOAD, 1); 
    curl_setopt($ch, CURLOPT_INFILE, $fp); 
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile)); 
    curl_setopt($ch, CURLOPT_NOPROGRESS, false); 
    curl_setopt($ch, CURLOPT_PROGRESSFUNCTION,function($resource,$dltotal, $dlnow, $ultotal, $ulnow){ 
      $progress = @round($ulnow/$ultotal * 100); 
      file_put_contents($this->progressFile, $progress); 
      flush(); 
     } 
    ); 
    curl_exec($ch); 
    $error_no = curl_errno($ch); 
    curl_close($ch); 
    if ($error_no == 0) { 
     echo $path; 
    } else { 
     echo false; 
    } 
} 
} 

$file = $_FILES['file']; 

$class = new Upload(); 
$class->progressFile = 'progressFile_' . $_GET['t'] . '.txt'; 
$class->up($file); 
+0

當您刷新網頁時,您嘗試實現的操作不可行,因此文件上載會中斷。 – khandelwaldeval

回答

0

你可以使用onbeforeunload(JavaScript的),併發送Ajax請求關閉卷曲

+0

我應該向他們發送ajax請求,以及php代碼關閉curl連接? –

+0

對不起,我忘了指定只有當你的php代碼將作爲守護進程運行時,它纔會起作用,因爲打開的資源Curl鏈接無法傳輸。無論如何, – Powar

+0

可能只是使用CURLOPT_TIMEOUT? – Powar