【问题标题】:how to randomly assign proxy for curl?如何为 curl 随机分配代理?
【发布时间】:2010-01-30 18:09:38
【问题描述】:

我希望我的 curl 使用 proxy.txt 文件中的随机代理,该文件以这种格式保存在我的站点中:

1.1.1.1:8080
2.2.2.2:8080
3.3.3.3:8080
...

我希望它随机生成,以便每次它使用 proxy.txt 列表中的不同代理,但我不知道我可以在 php 中编写类似的代码。

【问题讨论】:

    标签: php proxy curl


    【解决方案1】:

    从文件中随机读取一行:

    srand ((double)microtime()*1000000);
    $f_contents = file ("proxy.txt");
    $line = $f_contents[array_rand ($f_contents)];
    print $line;
    

    你现在只需要:

    function get_random_proxy()
    {
        srand ((double)microtime()*1000000);
        $f_contents = file ("proxy.txt");
        $line = $f_contents[array_rand ($f_contents)];
        return $line;
    }
    

    【讨论】:

      【解决方案2】:

      聚会迟到了,但想分享这个:

      基本上静态变量$proxys只被设置一次,并记住数组指针,所以每次你调用change_proxy()它都会给你文件中的下一个,然后在它循环一次后返回开始。

      function change_proxy()
      {
        static $proxys = file('./proxy.txt', FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
      
        $proxy = current($proxys);
        $end = next($proxys); # false when end
        if(!$end) {
          reset($proxys);
        }
        return $proxy;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 2013-09-23
        • 1970-01-01
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        • 2022-05-06
        • 1970-01-01
        相关资源
        最近更新 更多