Read line by TXT line and return to end (PHP)

1

I have the following function:

function pegarWS($numero){

    $PEGAR_WS = 'http://ws.com.br';
    $URL = $PEGAR_WS.$numero;

$proxies = file('pasta/secreta/inacessivel/via/http/proxies.txt');

//Limpa espaços em branco
$proxies = array_map(function ($proxy) {
    return trim($proxy);
}, $proxies);

// pegar random proxy


 $proxy_to_use = $proxies[ rand( 0, count( $proxies ) -1 ];

foo

This particular part: (need to adapt)

$proxy_to_use = $proxies[ rand( 0, count( $proxies ) -1 ];

Instead of fetching the proxy randomly (see code), I need to change it so it reads line by line from txt (one at a time) in loop. That is, read the first line, then the second, and so on .. When you get to the last line it goes back to the first line.

    
asked by anonymous 15.08.2018 / 01:23

1 answer

1

If I get it right, you can use recursion to do this. This way it will always return the next line and return to the first line whenever the file reaches the end. The limit is for .

function pegarWS($numero){

  $file = file("pasta/secreta/inacessivel/via/http/proxies.txt"); 
  if(isset($file[$numero])){
      return $file[$numero];
  }
  // se não existir o índice subtrai o número
  // envia para a mesma função até chegar ao índice 0
  return pegarWS ($numero - count($file));

}

for($i = 0; $i < 10; $i++){
    echo pegarWS($i);
}

A suggestion

Open the file only once.

$file = file("pasta/secreta/inacessivel/via/http/proxies.txt"); 
$linhas = [];
foreach($file as $linha){
    $linhas[] = $linha;
}

$y = 0;
for($i = 0; $i < 10; $i++){
    if(!isset($linhas[$y])){
        $y = 0;
    } 
    echo $linhas[$y];
    $y++;
}

Another option

Using session to save indexes

function pegarWS($numero){

    $PEGAR_WS = 'http://ws.com.br';
    $URL = $PEGAR_WS.$numero;

    $proxies = file('pasta/secreta/inacessivel/via/http/proxies.txt');

    //Limpa espaços em branco
    $proxies = array_map(function ($proxy) {
        return trim($proxy);
    }, $proxies);

    if(!isset($_SESSION['index'])){
        $index = $_SESSION['index'] = 0;
    } else {
        $index = $_SESSION['index'];
    }
    if(isset($proxies[$index])){
        $linha = $proxies[$index];
    } else {
        $linha = $proxies[0];
        $_SESSION['index'] = 0;
    }
    $_SESSION['index']++;

    $proxy_to_use = $linha;

    // ... resto do código
}
    
15.08.2018 / 03:14