?
Solved

php to provide random html for an ssi? To change daily, weekly not just randomly?

Posted on 2005-04-26
29
Medium Priority
?
339 Views
Last Modified: 2006-11-18
<?
$directoryName="comments/";

$pageExtension=".htm";

function displayAaPHPrandomPage($dirname, $extension){
  $dirhandle = opendir($dirname) or die("ERROR opening ".$dirname);
  while (false !== ($file = readdir($dirhandle))) {
  global $SCRIPT_NAME ;

    if ( !@is_dir($file) && (substr_count($file,$extension) !=0) && ( substr_count($SCRIPT_NAME,$file)==0)) {
      $filelist[] = $file;
       
    }
  }
  closedir($dirhandle);
 
  srand((double)microtime()*1000000);
  $pageNumber = rand(0, sizeof($filelist) - 1);
  $pageName=$dirname.$filelist[$pageNumber];

  include($pageName);  
 
  return ;
 
  }
?>

<?=displayAaPHPrandomPage($directoryName, $pageExtension)?>


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Does anyone know how I could change the php snippet above to suit my requirments.
I know nothing about how to approach this, but have used the script below to parse random html pages through an ssi to have element change on my sites. It's great!

However now I want to use it on another site to parse random results but on a daily or half daily rotation (even weekly would be fine)
Any chance  someone out there could tell me what I need to change?


Regards
Bangers
0
Comment
Question by:bangers3474
  • 17
  • 10
  • 2
29 Comments
 
LVL 6

Accepted Solution

by:
German_Rumm earned 2000 total points
ID: 13870571
Here you go.
Modifications to script:
now random number is stored in a file. Every $interval file will be recreated with new random number.
You will need to create file on your server and allow PHP to write to it (add write permissions)
Script attempts to create this file, but this may not work: by default php scripts don't have write access to add file to directory.

Don't forget to change $interval and $filename for your script and filesystem.
<?php

$directoryName="comments/";
$pageExtension=".htm";

function displayAaPHPrandomPage($dirname, $extension){
  $dirhandle = opendir($dirname) or die("ERROR opening ".$dirname);
  while (false !== ($file = readdir($dirhandle))) {
  global $SCRIPT_NAME ;

    if ( !@is_dir($file) && (substr_count($file,$extension) !=0) && ( substr_count($SCRIPT_NAME,$file)==0)) {
      $filelist[] = $file;
       
    }
  }
  closedir($dirhandle);
 
  srand((double)microtime()*1000000);
   
  $interval = '+12 hour';
  $filename = 'random.txt';

  if (!file_exists($filename)) touch($filename); // safeguard: if file does not exist, create it
  if (strtotime($interval, $mtime) < time()) { // random number "expired"
    $pageNumber = rand(0, sizeof($filelist) - 1); // create new random for next $interval
    file_put_contents($filename, $pageNumber); // this function is for PHP5 only
    // following line is for PHP4, uncomment it if necessary
    // $fp = fopen($filename, 'w'); fwrite($fp, $pageNumber); fclose($fp);
  } else {
    // use old random number
    $pageNumber = file_get_contents($filename);
  }
   
  $pageName=$dirname.$filelist[$pageNumber];
  include($pageName);  
  return ;
 
  }
?>
0
 

Author Comment

by:bangers3474
ID: 13873704
What do I need in random.txt or what will be written to random.txt?
Must admit I am a little confused why I need to create another file for this to work?
Also, providing it does work, how to I set it to change from 12hour delay to 1 week delay, do I just change  $interval = '+12 hour'?
regards
Bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13873869
As I understood you need that "random" include stayed for some interval.
During that interval that include should not change?

If so, then for that time we should not generate new random number and use previous. (in you script random number is generating every time the page is included)
We store our generated random number in random.txt, and change it only after $interval has passed.

And yes, if you want interval to be 1 week just set $interval = "+1 week";

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:bangers3474
ID: 13874220
Got it,
I'll give a go then award the points hopefully,
thanks for the help
bangers
0
 

Author Comment

by:bangers3474
ID: 13957509
German_Rumm,
I know I awarded the points but the script doesn't seem to work now that I have actually tested it. Can you see why?
please reply asap
bangers
0
 

Author Comment

by:bangers3474
ID: 13957523
p.s There is no error message it's just that results are not parsed to the page,
cheers
Bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13957946
bangers3474,

can you post link to that file. the same that gets included via SSI?
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13958109
German_Rumm,

Hmmm, try adding
    echo $pageName;
before
    include($pageName);

What will you get?
0
 

Author Comment

by:bangers3474
ID: 13958228
echo $pageName; same result, nothing. The code is below.
Does it need a statement at the end to write the results to the page or is it already included?
cheers bangers


<?php

$directoryName="../swimming-reviews/comments-shop/";//remember to leave a trailing slash to the directory "../directory1/"

$pageExtension=".txt";// in this case, we are randomly displaying .txt files (note the ".")

function displayRandomDelay($dirname, $extension){
  $dirhandle = opendir($dirname) or die("ERROR opening ".$dirname);
  while (false !== ($file = readdir($dirhandle))) {
  global $SCRIPT_NAME ;

    if ( !@is_dir($file) && (substr_count($file,$extension) !=0) && ( substr_count($SCRIPT_NAME,$file)==0)) {
      $filelist[] = $file;
       
    }
  }
  closedir($dirhandle);
 
  srand((double)microtime()*1000000);
   
  $interval = '+12 hour'; // time delay, can be changed to +1 week or +24 hour etc
  $filename = 'random.txt'; // path to simple txt file which holds a random generated result for as long as specified

  if (!file_exists($filename)) touch($filename); // safeguard: if file does not exist, create it
  if (strtotime($interval, $mtime) < time()) { // random number "expired"
    $pageNumber = rand(0, sizeof($filelist) - 1); // create new random for next $interval
    file_put_contents($filename, $pageNumber); // this function is for PHP5 only
    // following line is for PHP4, uncomment it if necessary
    // $fp = fopen($filename, 'w'); fwrite($fp, $pageNumber); fclose($fp);
  } else {
    // use old random number
    $pageNumber = file_get_contents($filename);
  }
   
  $pageName=$dirname.$filelist[$pageNumber];
  echo $pageName;
  include($pageName);  
  return ;
 
  }
?>

0
 

Author Comment

by:bangers3474
ID: 13958257
p.s: I created a file called random.txt, in the same file as the php script, which is cmod 777.
I take it that's okay?
regards
Bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13958280
bangers3474,

Well, I noticed that in you script you never call your function :-)
Add
    displayRandomDelay($directoryName, $pageExtension);
before your last ?>
0
 

Author Comment

by:bangers3474
ID: 13958378
Now I've got an error message:
Fatal error: Call to undefined function: file_put_contents() in /homepages/12/d68570427/htdocs/sws/swimming-shop/randomdelay.php on line 27

Here's the script:

<?php

$directoryName="../swimming-reviews/comments-shop/";//remember to leave a trailing slash to the directory "../directory1/"

$pageExtension=".txt";// in this case, we are randomly displaying .txt files (note the ".")

function displayRandomDelay($dirname, $extension){
  $dirhandle = opendir($dirname) or die("ERROR opening ".$dirname);
  while (false !== ($file = readdir($dirhandle))) {
  global $SCRIPT_NAME ;

    if ( !@is_dir($file) && (substr_count($file,$extension) !=0) && ( substr_count($SCRIPT_NAME,$file)==0)) {
      $filelist[] = $file;
       
    }
  }
  closedir($dirhandle);
 
  srand((double)microtime()*1000000);
   
  $interval = '+12 hour'; // time delay, can be changed to +1 week or +24 hour etc
  $filename = 'random.txt'; // path to simple txt file which holds a random generated result for as long as specified

  if (!file_exists($filename)) touch($filename); // safeguard: if file does not exist, create it
  if (strtotime($interval, $mtime) < time()) { // random number "expired"
    $pageNumber = rand(0, sizeof($filelist) - 1); // create new random for next $interval
    file_put_contents($filename, $pageNumber); // this function is for PHP5 only
    // following line is for PHP4, uncomment it if necessary
    // $fp = fopen($filename, 'w'); fwrite($fp, $pageNumber); fclose($fp);
  } else {
    // use old random number
    $pageNumber = file_get_contents($filename);
  }
   
  $pageName=$dirname.$filelist[$pageNumber];
  echo $pageName;
  include($pageName);  
  return ;
 
  }
  displayRandomDelay($directoryName, $pageExtension);
?>
0
 

Author Comment

by:bangers3474
ID: 13958419
Don't worry about that I uncommented the php 5 stuff and it worked.
However the results parse the contents of a file as well as the file name at the begining, is there anyway of removing the reference to the file name?
reagdrs
Bangers

p.s once this is sorted out  post to http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21417117.html and I'll give you another 500 points
0
 

Author Comment

by:bangers3474
ID: 13958482
Just removed the echo $pageName; which got rid of that.
However have now noticed there is no delay to the randomising no matter how many hours I set it to, it can't be writting to random.txt
regards
bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13959480
bangers3474,

Hmm, script does not get file modification date. Correct this line:
      if (strtotime($interval, $mtime) < time()) { // random number "expired"
to
      if (strtotime($interval, filemtime($filename)) < time()) { // random number "expired"
0
 
LVL 10

Expert Comment

by:mensuck
ID: 13959548
Hi

 Why do loop the directory first, you should setup a place holder check it's time then and only then loop to get the new include file if needed!

I'll give my example!

usage....
$dir = './path/to/include/files';
$ext = '.html';
$time = 4;
$file = 'default.html';

random_include ( $dir, $ext, $time, $file );

where as....

$dir = the directory to read from (do not include the trailing '/') windows = c:/path/to/include/files, linux = ./path/to/include/files
$ext = the file extension of the file to include ( .html ) including the '.' <= period
$time = in hours (1, 12, 24)
$file = a default file name, (used if no file is found in the directory)




// script

<?

function random_include ( $path, $type, $hours, $default )
{
      $holder = 'placeholder' . $type;
      $hours  = ( $hours * 3600 );

      $io = '';

      if ( file_exists ( $path . '/' . $placeholder ) )
      {
            if ( ( $hours + filemtime ( $path . '/' . $placeholder ) ) > time () )
            {
                  $io = fread ( fopen ( $path . '/' . $placeholder, 'r' ), filesize ( $path . '/' . $placeholder ) );
            }

            clearstatcache ();
      }

      if ( empty ( $io ) )
      {
            $io = new_random_type ( $path, $type, $holder, $default );
      }

      include_once ( $path . '/' . $io );
}

function new_random_type ( $dir, $ext, $holder, $other )
{
      $list = array ();
      $real = '';

      if ( $io = @opendir ( $dir ) )
      {
            while ( ( $file = readdir ( $io ) ) !== false )
            {
                  if ( $file != '.' && $file != '..' )
                  {
                        $real = $io . '/' . $file;

                        if ( is_file ( $real ) && ! preg_match ( '!placeholder!', $file ) )
                        {
                              if ( get_extension ( $file, $ext ) )
                              {
                                    $list[] = $file;
                              }
                        }
                  }
            }

            closedir ( $io );
      }

      if ( empty ( $list ) )
      {
            $insert = $default;
      }
      else
      {

            $real = array_rand ( $list )

            $insert = $list[$insert];
      }

      $io = fopen ( $dir . '/' . $holder, 'w' );
      fputs ( $io, $insert );
      fclose ( $io );

      return ( $insert );
}

function get_extension ( $name, $end )
{
      return ( ( substr ( $name, strrpos ( $name, '.' ) ) == $end ? true : false ) );
}


?>


Suzanne

0
 
LVL 10

Expert Comment

by:mensuck
ID: 13959588
Hi

In the script......

I made changes to $var(s) that I did not change everywhere, here is the script fixed....

Sorry

<?

function random_include ( $path, $type, $hours, $default )
{
     $holder = 'placeholder' . $type;
     $hours  = ( $hours * 3600 );

     $io = '';

     if ( file_exists ( $path . '/' . $holder ) )
     {
          if ( ( $hours + filemtime ( $path . '/' . $holder ) ) > time () )
          {
               $io = fread ( fopen ( $path . '/' . $holder, 'r' ), filesize ( $path . '/' . $holder ) );
          }

          clearstatcache ();
     }

     if ( empty ( $io ) )
     {
          $io = new_random_type ( $path, $type, $holder, $default );
     }

     include_once ( $path . '/' . $io );
}

function new_random_type ( $dir, $ext, $holder, $other )
{
     $list = array ();
     $real = '';

     if ( $io = @opendir ( $dir ) )
     {
          while ( ( $file = readdir ( $io ) ) !== false )
          {
               if ( $file != '.' && $file != '..' )
               {
                    $real = $io . '/' . $file;

                    if ( is_file ( $real ) && ! preg_match ( '!placeholder!', $file ) )
                    {
                         if ( get_extension ( $file, $ext ) )
                         {
                              $list[] = $file;
                         }
                    }
               }
          }

          closedir ( $io );
     }

     if ( empty ( $list ) )
     {
          $insert = $default;
     }
     else
     {

          $real = array_rand ( $list )

          $insert = $list[$insert];
     }

     $io = fopen ( $dir . '/' . $holder, 'w' );
     fputs ( $io, $insert );
     fclose ( $io );

     return ( $insert );
}

function get_extension ( $name, $end )
{
     return ( ( substr ( $name, strrpos ( $name, '.' ) ) == $end ? true : false ) );
}


?>


Suzanne
0
 

Author Comment

by:bangers3474
ID: 13960616
German_Rumm,
I do not receive any results with the change (I also don't receive an error message). Any more thoughts?
Regards
Bangers
0
 

Author Comment

by:bangers3474
ID: 13960641
Suzanne,
Just going to give your script a go now,
cheers
Bangers
0
 

Author Comment

by:bangers3474
ID: 13960758
mensuck,
what and where do I need to change your script? so that I point to my files/default file have the right extension and time?:

I am but a simple man who needs to be told where things are..typical,
regards
bangers
0
 

Author Comment

by:bangers3474
ID: 13960797
German_Rumm & mensuck,
Just to let you know I will except both your correct scripts. If they both work I'll award 500 points by opening another question and accepting you post to the question.
regards
lee

p.s (German_Rumm I have already done this for you)
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13960820
bangers3474,

Just tell me, does it work now?
0
 

Author Comment

by:bangers3474
ID: 13960844
No.

German_Rumm,
I do not receive any results with the change (I also don't receive an error message). Any more thoughts?
Regards
Bangers
0
 

Author Comment

by:bangers3474
ID: 13966679
Any more thoughts?
Regards
Bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13966844
bangers3474,

Wait a little. I'm writing you modification of the script, will post it in a few minutes.
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13966905
bangers3474,

Here you go. A little more secure script and simpler to understand.
Set $directory, $extension, $interval, $filename to your values and give it a go. If there are some error messages - post them here.

<?php
    $directory = 'Q_21403331'; // directory, in what to look for "comments"
    $extension = '.txt'; // "comment" extension
   
    $interval = '+30 second'; // random number regeneration interval
    $filename = 'random.txt'; // name of file in which to store random number
   
    error_reporting(E_ALL);
    function getFileList($dir, $ext) {
        $fileList = array();
       
        if (substr($dir, -1) != '/') $dir .= '/';
        $dh = opendir($dir) or die("Error: Could not open directory ".$dir);
        while (false !== ($file = readdir($dh))) {
            $fullPath = $dir.$file;
            if (!is_dir($fullPath) && substr($file, -strlen($ext)) == $ext) {
                $fileList[] = $fullPath;
            }
        }
        closedir($dh);
        return $fileList;
    }
   
    $fileList = getFileList($directory, $extension);
    if (file_exists($filename)) {
        if (strtotime($interval, filemtime($filename)) < time()) {
            $randomIndex = array_rand($fileList);
            $fp = @fopen($filename, 'w');
            if ($fp === false) {
                die('Error: Could not open '.$filename.' for writing');
            }
            if (@fwrite($fp, $randomIndex) === false) {
                die('Error: Can not write to '.$filename);
            }
            fclose($fp);
        } else {
            $randomIndex = file_get_contents($filename);
        }
        if (isset($fileList[$randomIndex]) && file_exists($fileList[$randomIndex])) {
            readfile($fileList[$randomIndex]);
        } else {
            echo 'File could not be included (doesn\'t exist?)';
        }
    } else {
        die ('Error: Could not find '.$filename);
    }
?>

Example of this script is here: http://www.car.ee/EE/Q_21403331.php
Source code - here: http://www.car.ee/EE/Q_21403331.php?showSource=1
0
 

Author Comment

by:bangers3474
ID: 13967126
To quote the words of Ronald McDonald "I'm lovin' it!"

Post to the question I opened on this topic and I'll sort you out with another 500 points.
http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21417117.html

regards
Bangers.

p.s I might have to develop a bespoke content management system in php with a mysql database, would you be interested in the development if it came up. and would you be able to give me a quote - what's your going rate!

Thanks for all the help
Bangers
0
 
LVL 6

Expert Comment

by:German_Rumm
ID: 13967184
bangers3474,

Thanks! :-)
Contact me by MSN or email - it's in my member's profile :-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question