好吧,我在向不和諧API發出請求時遇到問題,我不明白curl是如何工作的。這是我的代碼:function make_request($mixed, $token, $get_json = true) { $url = is_string($mixed) ? $mixed : getApiUrl($mixed); // TODO: Check for valid url! $log_file = __DIR__.'/../logs/request.txt'; if(!is_readable($log_file)) printError("File '$log_file' is not readable!"); if(!is_writable($log_file)) printError("File '$log_file' is not writable!"); $ch = curl_init(); $f = fopen($log_file, 'w+'); if($f === false) printError("There was an error opening '$log_file'!"); ftruncate($f, 0); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_HTTPHEADER => array('Authorization: Bot ' . $token), CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_STDERR => $f, )); $response = curl_exec($ch); fclose($f); curl_close($ch); $contents = file_get_contents($log_file); if($contents != '') { // Censor bot key! $contents = preg_replace("/^Authorization: Bot.+?$/", "Authorization: Bot xxx", $contents); printError($contents); } if($get_json) { $pretty = isset($_GET["pretty"]); if($pretty) { $json = json_decode($response); return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } return $response; } return json_decode($response, true);}我的問題是,當 curl 只顯示冗長的日志時,也許我正在打印錯誤,但我不確定是用于打印錯誤還是整個日志。CURLOPT_STDERR在文檔上:https://www.php.net/manual/en/function.curl-setopt.php將錯誤輸出到的替代位置,而不是 STDERR。也許是因為啟用了。CURLOPT_VERBOSETRUE 表示輸出詳細信息。將輸出寫入 STDERR 或使用 CURLOPT_STDERR指定的文件。在這種情況下,我需要知道何時發生錯誤。這里有任何提示嗎?
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
您走在正確的軌道上。如果需要診斷輸出,則必須在發出請求之前安排捕獲它。通常的方法是將其存儲在RAM中,檢查卷曲錯誤并進行適當的處理。
該代碼如下所示:
$ch = curl_init();
curl_setopt_array($ch, [
// ... other options here
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_STDERR => ($log = fopen('php://temp', 'w')),
]);
$response = curl_exec($ch);
if (false === $response) {
$errno = curl_error($ch);
$errmsg = curl_strerror($errno);
$logtext = stream_get_contents($log, -1, 0);
// ... log the info above, take action, etc.
} else {
// ... $response is your HTTP response
}
curl_close($ch);
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報
0/150
提交
取消