file_get_contents同步或异步

时间:2014-02-28 20:22:05

标签: php curl asynchronous file-get-contents

今天我遇到了一种情况。

我正在使用file_get_contents从用户的文件中获取令牌。

$data=file_get_contents("http://example.com/aaa.php?user=tester&akey=abcdef1234");
$dec=json_decode($data,true);
$tokenid=$dec['message']['result']['tokenid'];

使用令牌我会调用另一个文件来获取详细信息;

$data=file_get_contents("http://example.com/bbb.php?user=tester&token=".$tokenid);

问题是有时我没有得到tokenid,刷新页面后我得到它。

aaa.php没有问题,它的工作正常。

我怀疑在转到第二个file_get_contents

之前,php是否还没等待令牌file_get_contents(asynchronous);的响应

我也尝试过curl但有时候我没有得到tokenid。我没有遇到过这类问题。

3 个答案:

答案 0 :(得分:5)

file_get_contents是同步的。有时候,由于网络故障,DNS失败等原因不同,您可能会获得FALSE

使用curl:它是faster并且可以自定义。如果您需要100%成功,可以wait for good response recursive

答案 1 :(得分:1)

绝对不是同步与异步的问题。但是调试是非常不可能的。尝试这样的事情。 die语句很难看,但说明了您可能想要合并的验证...

$data = file_get_contents("http://example.com/aaa.php?user=tester&akey=abcdef1234");
if (empty($data)) die('Failed to fetch data');

$dec = json_decode($data, true);
if (is_null($dec) || $dec === false) die('Failed to decode data');

$tokenid = isset($dec['message']['result']['tokenid']) ? $dec['message']['result']['tokenid'] : null;
if (is_null($tokenid) die('Token ID is not set');

//...

$data=file_get_contents("http://example.com/bbb.php?user=tester&token=".$tokenid);

猜测可能是您的令牌有时包含'特殊'需要转义的字符。

答案 2 :(得分:-1)

等待file_get_contents的最佳方法,希望对您有所帮助。

if ($result = file_get_contents("http://exemple.com", false)) {
 echo $result; // for exemple
}
相关问题