简体   繁体   English

PHP检查内容是否可用

[英]PHP check if contents are available

I am using random.org in my php script to generate random numbers like that: 我在我的PHP脚本中使用random.org生成这样的随机数:

    function getToken($length){
        $r = explode('
',file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain'));
        $string = '';
        foreach ( $r as $char ) $string.=$char;
        return $string;
    }

but my university net denies such queries, so whenewer i test my project using university wifi, i dont get random numbers to be generated, and that means trouble. 但是我的大学网络拒绝此类查询,因此当我使用大学wifi测试我的项目时,我没有得到随机数,这意味着麻烦。

So, i before using this function, it needs to be chect if i can query random.org or not like that: 因此,在使用此功能之前,我是否可以查询random.org还是需要这样:

    if( site is accessible ) return getToken();
    else return false;

what would be the best way to check accesability? 检查可访问性的最佳方法是什么?

Myself i tried: 我自己尝试过:

    file_get_contents();

but it sends warnings,whenewer it fails, 但它会发送警告,如果更新失败,

    dns_get_record();

but i dont know if i can trust that, if it checks only dns name. 但是我不知道我是否可以信任它,如果它只检查DNS名称。 Please help! 请帮忙!

PS a pinging technique might proove usefull... PS ping技术可能会证明有用的...

You could just run file_get_contents with @ to supress errors and simply return when it doesn't give you a random number, resulting in something like: 您可以只运行带@ file_get_contents来抑制错误,并在不给您随机数时简单地返回,结果是:

function getToken($length){
    $number = @file_get_contents('http://www.random.org/integers/?num='.$length.'&min=0&max=9&col=1&base=10&format=plain');
    if($number === false) return null;
    $r = explode('',$number);
    $string = '';
    foreach ( $r as $char ) $string.=$char;
    return $string;
}

That being said, I seriously doubt if you really need to use random.org to generate random numbers. 话虽如此,我严重怀疑您是否真的需要使用random.org生成随机数。 PHP's own pseudo-random generator functions include openssl_random_pseudo_bytes that is said to generate "cryptographically strong" pseudorandom numbers: PHP自己的伪随机生成器函数包括openssl_random_pseudo_bytes ,据说可以生成“加密强度高”的伪随机数:

http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM