Pergunta

I need to display random Advertisement in my webpage. I am using separate files to display ads

i.e., 1.txt, 2.txt .. 10.txt

Each files should be displayed in every refresh of page. I mean 1.php should be displayed in first refresh and 2.php should be displayed on another refresh. It might be random. but all the pages should be displayed randomly

How can i do this using rand function in php ?

Here is what i tried.

$result_random = rand(1,10); 
if($result_random <= 2)
{ 
require ('ad1.txt');
} 

But i don't know how to proceed. How can i do this ?

Foi útil?

Solução

Here is the Codepen :

Here is the w3schools working

As simple :

<?php 
$result_random = rand(1,10); 
if($result_random <= 2){ 
require ('ad1.txt');
} 
else if($result_random <= 4){ 
require ('ad2.txt');
}
else if($result_random <= 6){ 
require ('ad3.txt');
}
else if($result_random <= 8){ 
require ('ad4.txt');
}
else { 
require ('ad5.txt');
} 
?>

Outras dicas

For more reference rand()

$result_random = rand(1,10); 
require ('ad'.$result_random.'.txt');

use like this if your .txt file name like, ad1.txt,ad2.txt

Check demo Codeviper , try this easiest way,

PHP

<?php
    $input = array("1.php", "2.php", "3.php", "4.php", "5.php");
    $rand_keys = array_rand($input, 2);

    echo $input[$rand_keys[0]] . "\n";   /* include $input[$rand_keys[0]]; */
    echo $input[$rand_keys[1]] . "\n";   /* include $input[$rand_keys[1]]; */
?>

include() - behavior occur warning so the rest of the script will still execute.

require() - behavior occur fatal error, which stops execution immediately.

So in this case you should use include() function instead of required() function,

Final PHP code,

<?php
    $input = array("1.php", "2.php", "3.php", "4.php", "5.php");
    $rand_keys = array_rand($input, 2);

    include $input[$rand_keys[0]]; 

    include $input[$rand_keys[1]];
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top