get content random url within txt file

0

I have several txt files inside a folder

/pasta/1.txt
/pasta/2.txt 

Etc ...

Within these files contains several urls

Exemplo:
/pasta/1.txt

conteúdo:
www.site.com/nome/jose.html
www.site.com/nome/joao.html



/pasta/2.txt
conteúdo:
www.site.com/nome/maria.html
www.site.com/nome/juliana.html

I need a code that when accessing the url:     www.site.com.br/sortear.php it accesses the folder / folder / chooses one of the files (.txt) randomly and captures a URL (eg: www.site.com/nome/jose.html) and access this url.

Can anyone help me?

    
asked by anonymous 04.07.2017 / 19:56

1 answer

0

This is pretty simple to do, there are N way to do this.

First you need to get the files, list of files you have in the folder, in this case assuming everything is within /pasta/ and are in .txt could use glob to get the paths of the files and then select one of them using some generator.

$Arquivos = glob('pasta/*.txt');
$ArquivoEscolhido = $Arquivos[random_int(0, count($Arquivos) - 1)];

Okay, we use random_int to select one of the files, $ArquivosEscolhidos will have the path of one of the files, which has been randomly selected.

Now just read the files, in this case using file() and select one of the lines, could do:

$Linhas = file($ArquivoEscolhido);
$LinhaEscolhida = $Linhas[random_int(0, count($Linhas) - 1)];

Done, you have now selected a line and can display using echo $LinhaEscolhida , for example, or if you want to redirect use header() view this.

The random_int is only available in PHP 7 and higher. You too, but could use Mersenne Twister, via mt_rand or shuffle , or use an LFSR / LGC via rand , if using PHP 7 or less. You can also use scandir with some code changes.

    
04.07.2017 / 20:15