duanshang9426 2013-04-26 19:47
浏览 36
已采纳

PHP检查内容是否可用

I am using random.org in my php script to generate random numbers like that:

    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.

So, i before using this function, it needs to be chect if i can query random.org or not like that:

    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. Please help!

P.S. a pinging technique might proove usefull...

  • 写回答

1条回答 默认 最新

  • duandun3178 2013-04-26 19:53
    关注

    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:

    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. PHP's own pseudo-random generator functions include openssl_random_pseudo_bytes that is said to generate "cryptographically strong" pseudorandom numbers:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题