2014-02-28 97 views
3

今天我遇到了一种情况。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); 

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

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

我怀疑是否PHP不等待令牌的file_get_contents的响应才去第二file_get_contents(asynchronous);

我与卷曲尝试过,但有时我没有得到tokenid。我没有遇到这类问题。

+8

'file_get_contents'肯定是同步的。一般来说PHP是同步的。 – Barmar

+2

“没有得到”如何? '$ data'出现空白?包含除json之外的其他内容,导致'$ dec'为空? f_g_c不是异步的,并且会在接收数据或底层网络内容超时之前阻塞。 –

+0

很多时候我收到json与tokenid,但有时我收到null。 – user1602452

回答

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); 

猜测可能是你的令牌有时含有“特殊”字符需要进行转义。

+0

我试过你的方法,有时候我收到'取数据失败'; 但刷新后我收到的数据。 – user1602452

+0

在我的情况下,令牌总是数值。 但aaa.php页面没有任何问题。每次运行aaa。PHP通过浏览器给它JSON输出 – user1602452

2

file_get_contents是同步的。由于网络故障,DNS故障等不同原因,您可能会得到FALSE

使用curl代替:它是faster和更多可定制的。如果您需要100%成功,您可以wait for good response recursive

+0

我认为这是不准确的,你可以从'file_get_contents'返回NULL。我们需要清楚'false!== NULL' – ficuscr

+0

你说的对,当然是'FALSE'。但我认为这并没有改变答案的本质。 –

+0

然后更新答案 –