get content Random url inside txt file

Asked

Viewed 143 times

0

I have several txt files inside a folder

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

Etc....

Inside 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/draw.php it accesses the folder /folder/ chooses one of the files (.txt) in a Random way and captures a URL (Ex: www.site.com/name/Jose.html) and access this url.

Someone can help me?

  • Marcelo, put the code you are trying to use to create this task, this way people can help you find the problem because from what it seems you are asking to do for you, and it will not happen...

  • And what do you mean by "access this URL"? PHP should make a request for the page or the user should be redirected?

  • @Andersoncarloswoss, redirected to url.

1 answer

0


This is quite simple to be done, there are N way to do this.

First you need to get the files, the list of files you have in the folder, in this case assuming that everything is inside of /pasta/ and are in .txt could use the 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 the random_int to select one of the files, the $ArquivosEscolhidos will have the path of one of the files, which was selected randomly.

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

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

Ready, now you have selected a line and can display using echo $LinhaEscolhida, for example or if you want to add header() see this.


The random_int is only available in PHP 7 and above. You could also use Mersenne Twister, via mt_rand or shuffle, or use an LFSR/LGC via rand, if you use PHP 7 or lower. You can also use scandir with some changes in the code.

  • I managed using what you forwarded

Browser other questions tagged

You are not signed in. Login or sign up in order to post.