(作業メモ 20260920) PHP で file_get_contents から curl への変更

20 9月

API サーバーとのやり取りにおいて、file_get_contents のところが問題になっているように思えて、curl を試してみました。その記録です。リクエストに長い時間がかかる場合の話です。

通信には、返事をもらうまでにいまのところ2、3分必要です。それがうまくいかない。

もとは下記のように書いていました。最初は timeout を書いていなかったのですが、あとで追加しています。

$postdata = http_build_query(array('base64data' => $tmpBase64, 'TAnsAndEtc' => $tmpBase64a));

$headers = array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: '.strlen($postdata)
    );

$context = stream_context_create([	
	'http' => ['method'  => 'POST',
		'header'=>implode( "\r\n", $headers),
		'ignore_errors' => true,
		'content' => $postdata,
		'timeout' => 300
	]	
]);

$res_base64 = file_get_contents($server . '/phpSimpleQuestion/allAnswerTest.php', false, $context);

timeout を追加して多少改善されたと思ったのですが、それでもかなりの確率で失敗します。そこで curl を使った下記のような記述に改めました。

$param = array('base64data' => $tmpBase64, 'TAnsAndEtc' => $tmpBase64a);

$url = $server . '/phpSimpleQuestion/allAnswerTest.php';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);

$res_base64 = curl_exec($ch);

curl_close($ch);


$res = base64_decode($res_base64);

上記も確実というわけではありませんが、まあだいたい成功します。

RequestToRemoteServer.php の中の記述です。採点差配サーバーのファイルなので、あとで忘れずに修正をかける必要があります。