首页 > 解决方案 > 我怎样才能使 php 可以从 txt 文件加载代理,然后在使用 curlopt_proxy 时“旋转”它们

问题描述

这是我尝试过的一些..我仍然收到错误调用成员函数getProxy()未定义变量:旋转,在我定义了getproxy函数之后,我想我是盲目的,因为有些东西我看不到,请如果你有一些建议,分享它:)。PS:我所说的旋转是通过随机化每个代理并在使用 curl “post”时使用它,如果这是一个糟糕的帖子,我很抱歉。


Class RotateProxy{
    private $proxy = '';
    private $fp = '';
    private $list = array();
    private $counter; //number of times proxy used. Default is 1
    private $current; //number of times proxy HAS been used.

    public function __constructor($path,$counter=1){
        $this->list = trim(file($path));
        $this->$counter = $counter;
    }

    public function getProxy(){
        if($this->current > $this->counter){
            array_shift($this->list);

            $this->current = 1;

            $this->proxy = $this->list[0];

            return $this->proxy;
        }else{
            $this->current++;
            return $this->proxy;
        }
    }
}

$proxylist = __DIR__ . 'proxies.txt'; // just an example.
$proxy = $rotate->getProxy();
$counter = 1; // proxy will be used 5 times before moving to the next proxy.
$rotate = new RotateProxy($proxylist,$counter);
$session = mt_rand();
$curl = curl_init('https://api.ipify.org/');
curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_PROXY, $proxy);
$result = curl_exec($curl);
curl_close($curl);



if ($result)
    echo $result;
?>```

标签: phpfilecurlproxy

解决方案


在调用实例上的方法之前,您必须创建 RotateProxy 类的实例。即这样:

$rotate = new RotateProxy($proxylist,$counter);
$proxy = $rotate->getProxy();

推荐阅读