file_get_contents synchronous or asynchronous

前端 未结 3 1147
花落未央
花落未央 2021-01-14 02:41

Today I came across one situation.

I am using file_get_contents to get token from a file for a user.

$data=file_get_contents(\"http://ex         


        
相关标签:
3条回答
  • 2021-01-14 02:58

    Definitely not a question of synchronous vs. asynchronous. But as is debugging is pretty impossible. Try something like this. The die statements are ugly but illustrates the validation you might want to incorporate...

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

    A guess might be your token sometimes contains 'special' characters that need to be escaped.

    0 讨论(0)
  • 2021-01-14 03:03

    file_get_contents is synchronous. You can get FALSE sometimes because of different reasons like network fail, DNS fail etc.

    Use curl instead: it's faster and more customizable. You can wait for good response recursive if you need 100% success.

    0 讨论(0)
  • 2021-01-14 03:11

    the best way to waiting for file_get_contents, i hop that help you.

    if ($result = file_get_contents("http://exemple.com", false)) {
     echo $result; // for exemple
    }
    
    0 讨论(0)
提交回复
热议问题