• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 349
  • Last Modified:

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

<?
$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
bangers3474
Asked:
bangers3474
  • 17
  • 10
  • 2
1 Solution
 
German_RummCommented:
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
 
bangers3474Author Commented:
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
 
German_RummCommented:
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
bangers3474Author Commented:
Got it,
I'll give a go then award the points hopefully,
thanks for the help
bangers
0
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
p.s There is no error message it's just that results are not parsed to the page,
cheers
Bangers
0
 
German_RummCommented:
bangers3474,

can you post link to that file. the same that gets included via SSI?
0
 
bangers3474Author Commented:
0
 
German_RummCommented:
German_Rumm,

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

What will you get?
0
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
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
 
German_RummCommented:
bangers3474,

Well, I noticed that in you script you never call your function :-)
Add
    displayRandomDelay($directoryName, $pageExtension);
before your last ?>
0
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
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
 
German_RummCommented:
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
 
mensuckCommented:
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
 
mensuckCommented:
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
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
Suzanne,
Just going to give your script a go now,
cheers
Bangers
0
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
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
 
German_RummCommented:
bangers3474,

Just tell me, does it work now?
0
 
bangers3474Author Commented:
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
 
bangers3474Author Commented:
Any more thoughts?
Regards
Bangers
0
 
German_RummCommented:
bangers3474,

Wait a little. I'm writing you modification of the script, will post it in a few minutes.
0
 
German_RummCommented:
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
 
bangers3474Author Commented:
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
 
German_RummCommented:
bangers3474,

Thanks! :-)
Contact me by MSN or email - it's in my member's profile :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 17
  • 10
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now