2013-05-04 47 views
2

我正在寫一個腳本,其中未指定數量的文件需要通過cURL請求上傳到遠程API。但是,此腳本掛起並最終超時。奇怪的是,所有請求都成功(文件成功上傳),但腳本無法繼續。這是循環:在循環中使用cURL

foreach ($paths as $path) { 
    $ch = curl_init($path); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Token: '.$token, 'Content-Length: '.filesize($path)); 
    curl_setopt($ch, CURLOPT_PUT, true); 
    curl_setopt($ch, CURLOPT_INFILE, fopen($path, 'r')); 
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path)); 
    echo curl_exec($ch); 
} 

我相信這與循環有關。我試過在循環中添加curl_close,但它不能解決問題。有任何想法嗎?從環

+0

'所有的請求都successful' **和**'但腳本無法繼續'一起可能是不可能的(唯一的可能是腳本在成功上傳最後一張圖片後遇到問題) – hek2mgl 2013-05-04 06:27:02

+0

我知道這很奇怪,但文件出現在目標目錄中。我不知道該說什麼... – 2013-05-04 06:33:38

回答

3

函數把timeoutCURL

foreach ($paths as $path) { 
    $ch = curl_init($path); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Token: '.$token, 'Content-Length: '.filesize($path)); 
    curl_setopt($ch, CURLOPT_PUT, true); 
    curl_setopt($ch, CURLOPT_INFILE, fopen($path, 'r')); 
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path)); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds 
    echo curl_exec($ch); 
} 
+1

謝謝!通過添加超時,我終於能夠看到一些錯誤,我很容易解決。那時我能夠消除超時,一切都很好!我只是不確定排除故障的最佳方式 - 超時是一個竅門。 – 2013-05-04 06:54:36

+0

@大衛很高興幫助... :) – 2013-05-04 07:02:14

-1

單獨的捲曲與調用像下面

foreach ($paths as $path) { 
call_curl($path); 
} 


function call_curl($path){ 
    $ch = curl_init($path); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Token: '.$token, 'Content-Length: '.filesize($path)); 
    curl_setopt($ch, CURLOPT_PUT, true); 
    curl_setopt($ch, CURLOPT_INFILE, fopen($path, 'r')); 
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path)); 
    echo curl_exec($ch); 
} 
+0

謝謝。我現在正在嘗試,但我很好奇;爲什麼這會有所作爲? – 2013-05-04 06:34:46

+2

@David這沒有什麼區別。 – 2013-05-04 06:39:18