Solved

Unlink *.jpg using timer

Posted on 2008-10-31
19
482 Views
Last Modified: 2011-10-19
I have a index.php file in a folder together with some *.jpg photos that upload (ftp) automatic to a server.
The index.php is used so that the *.jpg are viewable in a browser (http://arvidkristiansen.com/web/bilde1.htm).
This folder will fill up with files, so i all *.jpg except the 10 most recent ones to automatic delete.
0
Comment
Question by:arvid_kristiansen
  • 9
  • 6
  • 3
  • +1
19 Comments
 
LVL 13

Expert Comment

by:Xyptilon2
ID: 22855702
You can use the following bash script and execute it from within php using exec(), try it first, make sure you've a backup and make sure you set the file to 755 permissions.

Change /home/folder/files  to whatever folder you are using


#!/bin/bash 
 

num_files='ls /home/folder/files | wc -l' 

num_to_delete='expr ${num_files} - 10' 

if [ ${num_to_delete} -gt 0 ]; then 

for i in 'ls /home/folder/files | head -n ${num_to_delete}'; do 

rm $i 

done 

fi 

Open in new window

0
 
LVL 43

Expert Comment

by:ravenpl
ID: 22855872
Xyptilon2: You should tell "ls" to sort by time, so 10 most recent files are left - not 10 random.

0
 

Author Comment

by:arvid_kristiansen
ID: 22859004
Im a newbe when it comes to PHP, can the above be explained a bit better? Maybe a compleet code with explanations to any varibles.
0
 
LVL 9

Expert Comment

by:absx
ID: 22865249
Hi,

Example below will remove all but 10 lates files from a defined directory. Is this helpful?
<?
 

$directory = "/my/path/";
 

// Check for directory existence 

file_exists($directory) or die("$directory doesn't exist\n");

$files = @scandir($directory) or die("$directory not a directory\n");
 

// Check for contents (. and .. don't count)

if(count($files)<=2)

	die("$directory is empty\n");

if(count($files)<=12)

	die("$directory has less than 10 files, no need to delete any\n");
 

// Get creation dates (filemtime() for modification date)

foreach($files as $file){

	if($file != "." && $file != "..")

		$filectimes[] = filectime($directory.$file).$file;

}
 

// Sort ascending by date

sort($filectimes);
 

// Loop until 10 remain

$i = count($filectimes)-1;

do {

	echo "Deleting (unlinking) ".$directory.substr($filectimes[$i],10).", creation date was ".date("Y-m-d H:i:s",substr($filectimes[$i],0,10))."\n";

	unlink($directory.substr($filectimes[$i],10)

	$i--;

} while ($i>10);
 

?>

Open in new window

0
 

Author Comment

by:arvid_kristiansen
ID: 22867303
Absx- I cant get your code to work. I have a folder named "cam3" containing the photos that are automatic uploaded and a "index.php" file as seen below. Where should your code go and what needs to be changed?
<?

// +----------------------------------------------------------------------+

// | Easy Image Photo Gallery Script 1.3                                  |

// +----------------------------------------------------------------------+

// | Copyright (c) 2005 www.php4script.com                                |

// +----------------------------------------------------------------------+

// | Author: www.php4script.com <support@php4script.com>                  |

// +----------------------------------------------------------------------+
 
 

/******************************* CONFIGURATION ********************************/
 

/* CSS settings
 

  To configure the look of the links and texts define the following classes in the your CSS file:

    `nav` for the navigation links

    `nav_current` for the current page digit

    `copy` for the `www.php4script.com` link and `Powered by` text

    `description` for the description if used
 

*/
 

/* sort mode: available values:

0 - sort by name asc

1 - sort by name desc

2 - sort by file time asc

3 - sort by file time desc

4 - sort by file size asc

5 - sort by file size desc

*/
 
 
 

//////////////////////////////////////////////////////////////////////////////

//

// NEED MORE FEATURES?

//

// Try our AZ Photo Album Script PRO

// http://php4script.com/php-photo-album-script/

//

// FEATURES

//

// * Free installation<br>

// * Watermark Support<br>

// * Mass changes: rotating/moving/sorting/deleting<br>

// * Automatic thumbnails generation<br>

// * Automatically resize photo to make it fit on the front-end display<br>

// * 3 types of navigation<br>

// * Password protected admin area<br>

// * Skins support<br>

// * Easy template system to make your own custom skins<br>

// * Fit easily into your web design<br>

// * Add, edit or delete photo categories<br>

// * Use FTP Uploading to help you speed up photos adding<br>

// * Set Photo Gallery display properties<br>

// * Easy installation (online installer)

// * and more...

//

////////////////////////////////////////////////////////////////////////////////
 
 

define(SORT_MODE, 0);
 
 

// read JPEG files (1 - yes, 0 - no)

define('READ_JPG', 1);
 

// read GIF files (1 - yes, 0 - no)

define('READ_GIF', 1);
 

// read PNG files (1 - yes, 0 - no)

define('READ_PNG', 1);
 

// hide the `IPGS 1.3` link (1 - hide, 0 - show)

define('HIDE_COPY', 0);
 

// header file

// if you need to use a header file you can specify a path to that file

define('HEADER_FILE', 'header.htm');
 

// footer file

// if you need to use a footer file you can specify a path to that file

define('FOOTER_FILE', 'footer.htm');
 
 

// culculate image size (1 - culculate 0 - not calculate)

define('CULC_IMAGE_SIZE', 1);
 
 
 

/*

If you want to have a some titles/descriptions for your photos just create 

a description.txt file at the same folder where script lacated
 

Fromat of description.txt file is: file_name::some_text
 

example:

photo1.jpg::My first photo

photo2.gif::My second photo
 
 

*/

// name of description file

define('DESCRIPTION_FILENAME', 'description.txt');
 
 
 
 

/************************  DO NOT EDIT ANY CODE BELOW *************************/

error_reporting(0);
 

// pagenav

define ("PAGENAV_PERPAGE",15);

define ("PAGENAV_TOTALRECS",355);

define ("PAGENAV_MINPAGES",6);

define ("PAGENAV_MAXPAGES",10);

define ("PAGENAV_CURRPAGEOFFSET",-1);

define ("PAGENAV_PERSET",10);

define ("PHOTOS_PER_PAGE", 1);
 
 

$p = split('/', $_SERVER['SCRIPT_FILENAME']);

$script_name = $p[count($p)-1];

$path = str_replace($script_name, '', $_SERVER['SCRIPT_FILENAME']);
 

$allowed_ext = array();

if(READ_JPG == 1) {

  array_push($allowed_ext, 'jpg');

}

if(READ_GIF == 1) {

  array_push($allowed_ext, 'gif');

}

if(READ_PNG == 1) {

  array_push($allowed_ext, 'png');

}
 
 

$path = './';

$dir = dir($path);

if(empty($_GET['start'])) $_GET['start'] = 1;
 
 

$c0 = array(60,98,114,62,60,100,105,118,32,97,108,105,103,110,61,34,99,101,110,116,101,114,34,32,115,116,121,108,101,61,34,102,111,110,116,45,102,97,109,105,108,121,58,118,101,114,100,97,110,97,59,102,111,110,116,45,115,105,122,101,58,56,112,120,59,99,111,108,111,114,58,115,105,108,118,101,114,59,34,62,60,97,32,116,105,116,108,101,61,34,69,97,115,121,32,73,109,97,103,101,32,80,104,111,116,111,32,71,97,108,108,101,114,121,32,83,99,114,105,112,116,46,32,80,111,119,101,114,101,100,32,98,121,32,104,116,116,112,58,47,47,119,119,119,46,112,104,112,52,115,99,114,105,112,116,46,99,111,109,34,32,115,116,121,108,101,61,34,102,111,110,116,45,102,97,109,105,108,121,58,118,101,114,100,97,110,97,59,102,111,110,116,45,115,105,122,101,58,56,112,120,59,99,111,108,111,114,58,115,105,108,118,101,114,59,34,32,99,108,97,115,115,61,34,99,111,112,121,95,108,105,110,107,34,32,104,114,101,102,61,34,104,116,116,112,58,47,47,119,119,119,46,112,104,112,52,115,99,114,105,112,116,46,99,111,109,47,63,105,100,61,49,34,62,60,115,112,97,110,32,99,108,97,115,115,61,34,99,111,112,121,34,62,80,104,111,116,111,32,71,97,108,108,101,114,121,32,83,99,114,105,112,116,32,118,49,46,51,60,47,115,112,97,110,62,60,47,97,62,60,47,100,105,118,62);

$c1 = array(60,97,32,116,105,116,108,101,61,34,69,97,115,121,32,73,109,97,103,101,32,80,104,111,116,111,32,71,97,108,108,101,114,121,32,83,99,114,105,112,116,46,32,80,111,119,101,114,101,100,32,98,121,32,104,116,116,112,58,47,47,119,119,119,46,112,104,112,52,115,99,114,105,112,116,46,99,111,109,34,32,104,114,101,102,61,34,104,116,116,112,58,47,47,119,119,119,46,112,104,112,52,115,99,114,105,112,116,46,99,111,109,47,63,105,100,61,49,34,62,60,105,109,103,32,97,108,116,61,34,69,97,115,121,32,73,109,97,103,101,32,80,104,111,116,111,32,71,97,108,108,101,114,121,32,83,99,114,105,112,116,46,32,80,111,119,101,114,101,100,32,98,121,32,104,116,116,112,58,47,47,119,119,119,46,112,104,112,52,115,99,114,105,112,116,46,99,111,109,34,32,98,111,114,100,101,114,61,34,48,34,32,119,105,100,116,104,61,34,49,34,32,104,101,105,103,104,116,61,34,49,34,32,115,114,99,61,34,95,95,115,112,97,99,101,114,46,103,105,102,34,62,60,47,97,62);

$total_size = 0;

while ($file = $dir->read()) {

//  if(array_sum($c) != 16284) break;

  if (($file != '.') && ($file != 'CVS') && ($file != '..')) {

    $file_size = filesize($path . $file);

    

    $ext = file_ext($file);

    if(!is_dir($path . $file) && isset($ext) && in_array($ext, $allowed_ext)) {

      

      $images[] = array('name' => $file,

                        'last_modified' => filemtime($path . $file),

                        'size' => $file_size,

                         );

    }

  }

}
 
 

// sort order

$sort_mode = array(

0 => 'cmp_name_asc',

1 => 'cmp_name_desc',

2 => 'cmp_time_asc',

3 => 'cmp_time_desc',

4 => 'cmp_size_asc',

5 => 'cmp_size_desc',

);

uasort($images, $sort_mode[3]);
 

foreach($images as $_i => $_d) {

  $new_images[] = $_d;

}

$images = $new_images;

// end: sort order
 
 

if(count($images) <= 0) {

  echo 'No images found';

  exit;

}
 
 

$filename = $images[$_GET['start']-1]['name'];
 

$description = read_description();
 

if(file_exists($path . $filename)) {

  $imgsize_str = ' ';

  if(CULC_IMAGE_SIZE == 1) {

    $imgsize = getimagesize($path . $filename);

    $imgsize_str .= $imgsize[3];

  }

  

  if(isset($description[$filename])) {

    $descr = $description[$filename];

    $alt = trim($description[$filename]);

  } else {

    $alt = $filename;

  }

  

  $image = '<img alt="' . $alt . '" src="' . $filename . '"' . $imgsize_str . '>';

} else {

  $image = 'Image not found';

}
 
 

$nav = nav(count($images));

$image_html = '<tr><td align="center">' . $image . '</td></tr>';

$descr_html = '';

if(isset($descr)) {

  $descr_html = '<tr><td align="center" class="description">' . $descr . '</td></tr>';

}

$nav_html = '<tr><td align="center">' . $nav . '</td></tr>';
 

$output = '<table align="center">' . $nav_html . $image_html . $descr_html . '</table>';
 

if(file_exists(HEADER_FILE)) {

  echo implode('', file(HEADER_FILE));

}
 

echo $output;

$count = count(${'c'.HIDE_COPY});

print "\n\n\n";

for($i=0; $i < $count; $i++) {

  echo chr(${'c'.HIDE_COPY}[$i]);

}

print "\n\n\n";
 

if(file_exists(FOOTER_FILE)) {

  echo implode('', file(FOOTER_FILE));

}
 
 

function file_ext($file) {

  $extension = split("[.]", $file);

  $ext_file = $extension[count($extension)-1];

  return strtolower($ext_file);

}
 
 

function nav($total_rows) {

  $pagenav = new PageNavigator_ManualScroll($_GET['start'], PHOTOS_PER_PAGE, $total_rows, PAGENAV_PERSET, array('from'=>'start'));

  $pagenav->parametersNot = array('start');

  $pagenav->autoLoadFromQuery();

  $pagenav->getRange($pagenav->getCurrentPage(), $firstrec, $lastrec);

  return $pagenav->render();

}
 
 

function read_description() {

  global $path;

  $data = array();

  $d = array();

  if(file_exists($path . DESCRIPTION_FILENAME)) {

    $data = file($path . DESCRIPTION_FILENAME);

  }

  $num = count($data);

  if($num > 0) {

    for($i=0; $i < $num; $i++) {

      list($file, $descr) = split('::', $data[$i]);

      $d[$file] = $descr;

    }

  }

  return $d;

}
 
 
 
 

class PageNavigator

{

    /**

    * Number of the current page.

    *

    * @var      integer

    * @access   private

    */

    var $current_page;
 

    /**

    * Number of records per one page.

    *

    * @var      integer

    * @access   private

    */

    var $records_per_page;
 

    /**

    * Total records in the data set.

    *

    * @var      integer

    * @access   private

    */

    var $total_records = 0;
 

    /**

    * Processed query string.

    *

    * @var      integer

    * @access   private

    */

    var $processed_query;
 

    /**

    * Number of pages. This is a cached copy.

    *

    * @var      integer

    * @access   private

    */

    var $totalpages;
 

    /**

    * Number of page to start with.

    *

    * @var      integer

    * @access   private

    */

    var $startpage;
 

    /**

    * Number of page to end with.

    *

    * @var      integer

    * @access   private

    */

    var $endpage;
 

    /**

    * Specifies which parameters go into produced query strings.

    *

    * @var      array

    * @access   private

    */

    var $query_vars;
 

    /**

    * String to print instead of a link / navigation label if there is none.

    *

    * @var      string

    * @access   private

    */

    var $empty_cell = '&nbsp;';

    

    /**

    * String parametrs unnecessary parameters in navigation link.

    *

    * @var      string

    * @access   private

    */

    var $parametersNot ='';

    

    /**

    * String accompaniment necessary parameter in navigation link.

    *

    * @var      string

    * @access   private

    */

    var $parametersGet ='';
 

    /**

    * Constructor. Initializes the PageNavigator object with the most important

    * properties.

    *

    * @param    integer    current page number

    * @param    integer    number of records per one page

    * @param    integer    total records. May be initialized later.

    * @return   void

    * @access   public

    */

    function PageNavigator($current_page=0, $records_per_page=15, $total_records=0, $query_vars='')

    {

        $this->setCurrentPage($current_page); //

        $this->setRecordsPerPage($records_per_page);

        $this->setRecordCount($total_records);
 

        $this->setQueryVars($query_vars);
 

    } // end func PageNavigator
 

    /**

    * Sets the number of records to span.

    *

    * @param    integer    number of records in data set

    * @return   void

    * @access   public

    */

    function setRecordCount($rec_num)

    {

        $this->total_records = $rec_num;

    }
 

    /**

    * Returns the number of records to span.

    *

    * @return   integer

    * @access   public

    */  

    function getRecordCount()

    {

        return $this->total_records;

    }
 

    /**

    * Sets the current page.

    *

    * @param    integer    current page

    * @return   void

    * @access   public

    */

    function setCurrentPage($current_page)

    {

        if (empty($current_page) || $current_page <= 0) $current_page = 1;
 

        $this->current_page = $current_page;

    }
 

    /**

    * Returns the current page.

    *

    * @return   integer    current page

    * @access   public

    */

    function getCurrentPage()

    {

        return $this->current_page;

    }
 

    /**

    * Sets records per page.

    *

    * @param    integer    records per page

    * @return   void

    * @access   public

    */

    function setRecordsPerPage($records_per_page)

    {

        $this->records_per_page = $records_per_page;

    }
 

    /**

    * Returns records per page.

    *

    * @return   integer    records per page

    * @access   public

    */

    function getRecordsPerPage()

    {

        return $this->records_per_page;

    }
 

    /**

    * Returns total number of pages using number of records and

    * records per page (already saved to object member variables).

    *

    * @return   integer    total number of pages

    * @access   public

    */

    function getTotalPages()

    {

        return ceil($this->total_records / $this->records_per_page);

    }
 

    /**

    * Sets query string variables to purge from / save to target query string

    *

    * @return   void

    * @access   public

    */

    function setQueryVars($vars='')

    {

        if (!is_array($vars)) $vars = array('page'=>'page');
 

        $this->query_vars = $vars;

    } // end func setQueryVars
 

    /**

    * Returns the start and end record for the given page by reference.

    *

    * @return   boolean    false if the given page exceeds the total

    * number of pages and true if calculations are successful

    * @access   public

    */

    function getRange($pagenum, &$startrecord, &$endrecord)

    {

        if ($pagenum > $this->getTotalPages())

        {

            return false;

        }

        

        // calculate start record

        $startrecord = ($pagenum==1 ? 1 : (($pagenum - 1) * $this->records_per_page) + 1);
 

        // calculate end record

        $endrecord = $startrecord + $this->records_per_page - 1; // initial

        if ($endrecord > $this->total_records)

            $endrecord = $this->total_records; // fix if out of bounds
 

        return true;

    } // end func getRange
 

    /**

    * Returns the page number given the start record and number of records

    * per one page

    *

    * @return   integer    page number that corresponds to the passed parameters

    * @access   public

    */

    function toPage($startrec, $records_per_page)

    {

        $page = ($startrec > 0 ? ceil($startrec / $records_per_page) : 1);
 

        return $page;

    } // end func toPage
 

/*

* METHODS TO OVERRIDE IN CUSTOM CLASSES

*/
 

    function preCalculateParameters()

    {

        $this->totalpages = $this->startpage = $this->endpage = 0;

    }

    

    function render()

    {

        die('PageNavigator::Render needs to be overridden.');

    }

    function formatActivePage($pagenum)

    {

        return "<b class=nav_current>$pagenum</b>&nbsp;&nbsp;";

    }

    function formatPage($pagenum)

    {

        return "<a class=nav  href=\"".$this->getTargetUrl($pagenum)."\"><u>$pagenum</u></a>&nbsp;&nbsp;";
 

    }

    function formatMovePrevious($pagenum)

    {

        return "<a class=nav  href=\"".$this->getTargetUrl($pagenum)."\"><u>&lt;</u></a>&nbsp;&nbsp;";

    }

    function formatMoveNext($pagenum)

    {

        return "<a class=nav  href=\"".$this->getTargetUrl($pagenum)."\"><u>&gt;</u></a>&nbsp;&nbsp;";

    }

    function formatMovePrevSet($pagenum)

    {

        return "<a class=nav  href=\"".$this->getTargetUrl($pagenum)."\"><u>&lt;&lt;</u></a>&nbsp;&nbsp;";

    }

    function formatMoveNextSet($pagenum)

    {

        return "<a class=nav  href=\"".$this->getTargetUrl($pagenum)."\"><u>&gt;&gt;</u></a>&nbsp;&nbsp;";

    }

    function formatHeader()

    {

        return "";

    }

    function formatFooter()

    {

        return "\n";

    }

    

/*

* PRIVATE UTILITY METHODS

*/
 

    /**

    * Counts results contained in an sql query by constructing

    * a special sql query from given params and executing it 

    * against the database identifier (uses PHPLIB)

    *

    * @param    resource   database resource identifier

    * @param    string     if $tablejoin_valid is false, this is the entire

    *                      SQL statement. If $tablejoin_valid is true, 

    *                      this is only the entire valid table join.

    * @param    string     SQL WHERE clause

    * @param    boolean    true if the second parameter is to be used as 

    *                      the list of tables (join) to use. False if

    *                      the second parameter is to be used as the entire

    *                      SQL statement.

    *

    * @return   integer    number of records in the data set

    * @access   public

    */

    function countDbRecords(&$DB, $sql_table_join, $where_clause="", $tablejoin_valid=true)

    {

        $ret = 0; // default return value

        

        if ($tablejoin_valid == true)

        {

            $sql = "SELECT COUNT(*) AS num from $sql_table_join ";

            if (empty($where_clause) || 

                strpos(' '.strtolower($where_clause), 'where') == 0)

            {

                $sql .= "WHERE ";

            }

            $sql .= $where_clause;

        }

        else

        {

            $sql = $sql_table_join;

        }

        

        $query = new query($DB, $sql);

        $row = $query->getrow();

        if (is_array($row))

        {

            $ret = (int)$row['num'];

        }

        $query->free();
 

        return $ret;

    } // end func countDbRecords
 

    /**

    * Automatically loads and sets current page variables within PageNavigator.

    *

    * @return   void

    * @access   public

    */

    function autoLoadFromQuery()

    {

        if (is_array($this->query_vars))

        {

            if (isset($this->query_vars['page']))

            {

                $var = $this->query_vars['page'];

                

                $this->setCurrentPage($_GET[$var]);

            }

            elseif (isset($this->query_vars['from']))

            {

                // adjust records per page if necessary

                if (isset($this->query_vars['count']))

                {

                    $var = $this->query_vars['count'];

                    

                    $this->setRecordsPerPage($_GET[$var]);

                }

                // load current page

                $var = $this->query_vars['from'];

                

                $this->setCurrentPage( 

                    $this->toPage($_GET[$var], $this->getRecordsPerPage())

                    );

            }

        }

    } // end func autoLoadFromQuery
 

    /**

    * Clears the query string of all variables that are needed

    * by this class (i.e. $page or $from/$to, $from/$num) and returns it.

    *

    * @param    array     array of strings identifying variables that need to be stripped from the current URI query string

    * @return   string    stripped query string

    * @access   public

    */

    function getStrippedQueryString($vars_array)

    {

        $query_vars = $_GET;

        

        // strip control variables

        foreach ($vars_array as $v)

        {

            unset($query_vars[$v]);

        }

        $qr = '';

        foreach ($query_vars as $k=>$v)

        {

            $qr .= $k.'='.urlencode($v).'&';

        }

        if (!empty($qr)) $qr = substr($qr, 0, -1);

        

        return $qr;

    } // end func getStrippedQueryString
 

    /**

    * Returns the link to jump to.

    *

    * @return   string    target link

    * @access   private

    */

    function getTargetUrl($pagenum)

    {

        

        $query_str = $this->processed_query;

        

        $query_str = $this->get_all_get_params($this->parametersNot);
 

        if (!empty($query_str))

        {

            $query_str .= "&";

        }
 
 

        return str_replace('//', '/', $_SERVER['PHP_SELF'])."?".$query_str.$this->prepareQueryVars($pagenum).$this->parametersGet;
 

    } // end func getTargetUrl
 
 

    /**

    * Returns the link without params in $exclude_array to jump to.

    *

    * @return   string    target link

    * @access   private

    */

    function get_all_get_params($exclude_array = '') {

      

      if ($exclude_array == '') $exclude_array = array();

      $get_url = '';

      reset($_GET);

      while (list($key, $value) = each($_GET)) {

        if (($key != 'error') && (!in_array($key, $exclude_array))) $get_url .= $key . '=' . $value . '&';

      }

      return substr($get_url, 0, -1);

    }
 
 

    /**

    * Returns a string to be inserted into the URL to switch pages

    * (i.e. page=2 or start=11&limit=10, etc). Override this to parse in

    * the manner you see fit)

    *

    * @param    integer    number of page

    * @return   string     string tobe inserted into the URL

    * @access   private

    */

    function prepareQueryVars($pagenum)

    {

        if (is_array($this->query_vars))

        {

            if (isset($this->query_vars['page']))

            {

                $ret = $this->query_vars['page'].'='.$pagenum;

            }

            elseif (isset($this->query_vars['from']))

            {

                $from = ($pagenum * $this->records_per_page) - $this->records_per_page + 1;

                

                if (isset($this->query_vars['count']))

                {

                    $ret = $this->query_vars['from'].'='.$from.'&'.

                        $this->query_vars['count'].'='.

                        $this->records_per_page;

                }

                else

                {

                    $ret = $this->query_vars['from'].'='.$from;

                }

            }

        }

        return $ret;
 

    } // end func prepareQueryVars
 

    /**

    * Caches the copy of the query string, first purging it of all variables

    * like page, from, to, etc, depending on what the developer intends to do

    *

    * @return   void

    * @access   private

    */

    function setProcessedQueryString()

    {

        $this->processed_query =

                    $this->getStrippedQueryString($this->query_vars);

    } // end func setProcessedQueryString
 

} // end class PageNavigator
 
 

class PageNavigator_ManualScroll extends PageNavigator

{

    /**

    * Number of pages to show within one set of pages.

    *

    * @var      integer

    * @access   private

    */

    var $pages_per_set;
 

    /**

    * Constructor. Initializes the PageNavigator_ManualScroll object with the 

    * most important properties.

    *

    * @param    integer    current page number

    * @param    integer    number of records per one page

    * @param    integer    total records. May be initialized later.

    * @param    integer    number of pages to be displayed per one set of

    *                      pages. If there are more pages than this figure, 

    *                      the button rendered by formatMoveNextSet() will be

    *                      available to the right. Same for the left button

    *                      navigating the user to the previous set of pages.

    * @return   void

    * @access   public

    */

    function PageNavigator_ManualScroll($current_page=0, $records_per_page=15, $total_records=0, $pages_per_set=10, $query_vars='')

    {

        PageNavigator::PageNavigator($current_page, $records_per_page, $total_records, $query_vars);
 

        $this->pages_per_set = $pages_per_set;
 

    } // end func
 

    /*

    PagesPerSet

    */

    function setPagesPerSet($pages_per_set)

    {

        $this->pages_per_set = $pages_per_set;

    }

    function getPagesPerSet()

    {

        return $this->pages_per_set;

    }
 

    /**

    * Returns the set we are on.

    *

    * @return   integer    current set of pages

    * @access   public

    */

    function getCurrentSet()

    {

        return floor(($this->current_page - 1) / $this->pages_per_set);

    }
 

    function preCalculateParameters()

    {

        $this->totalpages = $this->getTotalPages();

        

        $this->startpage = ($this->getCurrentSet() * $this->pages_per_set) + 1;
 

        if (($this->startpage + $this->pages_per_set - 1) > $this->totalpages)

        {

            $this->endpage = $this->totalpages;

        }

        else

        {

            $this->endpage = $this->startpage + $this->pages_per_set - 1;

        }

    } // end func preCalculateParameters
 

    function render()

    {

        // do not allow to proceed if not initialized correctly

        if ($this->total_records == 0)

        {

            return false;

        }

        

        // HEADER

        $output = $this->formatHeader();

        

        // GET INITIAL VARS

        $this->preCalculateParameters(); // calculate totalpages, startpage, endpage

        $set = $this->getCurrentSet();
 

        // CACHE QUERY STRING STRIPPED OF VARIABLES NEEDED BY THIS CLASS

        $this->setProcessedQueryString();

        

        // first generate all cells containing links to various pages

        $pages = '';

        for ($int = $this->startpage; $int <= $this->endpage; $int++)

        {

            $pages .= ( ($int == $this->current_page) ?

                    $this->formatActivePage($int) :

                    $this->formatPage($int) );
 

        }

        

        //  LINK TO PREVIOUS SET

        if ($set > 0)

        {

            $prevset = $this->formatMovePrevSet($this->current_page - $this->pages_per_set);

        } 

        else

        {

            $prevset = $this->empty_cell;

        }

        

        //  LINK TO PREVIOUS PAGE

        if ($this->current_page > 1)

        {

            $prevpage = $this->formatMovePrevious($this->current_page - 1);

        }

        else

        {

            $prevpage = $this->empty_cell;

        }
 

        //  LINK TO NEXT PAGE

        if ($this->current_page < $this->totalpages)

        {

            $nextpage = $this->formatMoveNext($this->current_page + 1);

        }

        else

        {

            $nextpage = $this->empty_cell;

        }
 

        //  LINK TO NEXT SET

        if ( ($this->endpage + 1) <= $this->totalpages )

        {

            $nextset = $this->formatMoveNextSet($this->endpage + 1);

        }

        else

        {

            $nextset = $this->empty_cell;

        }

        

        // RENDER PAGE NAVIGATION VIEW

        $output .= $prevset.$prevpage.$pages.$nextpage.$nextset;

        

        // ADD TABLE FOOTER

        $output .= $this->formatFooter();

        

        return $output;

    } // end func render
 

} // end class PageNavigator_ManualScroll
 
 

function cmp_name_asc(&$a, &$b) 

{ 

    if ($a['name']==$b['name']) return 0; 

        return ($a['name']<$b['name']) ? -1 : 1; 

}

function cmp_name_desc(&$a, &$b) 

{ 

    if ($a['name']==$b['name']) return 0; 

        return ($a['name']>$b['name']) ? -1 : 1; 

}

function cmp_time_asc(&$a, &$b) 

{ 

    if ($a['last_modified']==$b['last_modified']) return 0; 

        return ($a['last_modified']<$b['last_modified']) ? -1 : 1; 

}

function cmp_time_desc(&$a, &$b) 

{ 

    if ($a['last_modified']==$b['last_modified']) return 0; 

        return ($a['last_modified']>$b['last_modified']) ? -1 : 1; 

}

function cmp_size_asc(&$a, &$b) 

{ 

    if ($a['size']==$b['size']) return 0; 

        return ($a['size']<$b['size']) ? -1 : 1; 

}

function cmp_size_desc(&$a, &$b) 

{ 

    if ($a['size']==$b['size']) return 0; 

        return ($a['size']>$b['size']) ? -1 : 1; 

}
 
 

?>

Open in new window

0
 
LVL 9

Expert Comment

by:absx
ID: 22867522
Hi,

Sorry, a semicolon was missing from my previous example on line 28. To combine this functionality with your index.php (assuming you want to do this garbage collection every time a page is loaded), you can just insert the included script in any part of the page (say, to the very end to find it if needed later).

If there's another problem, please look for error messages at the bottom of the page, this might be helpful.
function deleteOldFiles($directory) {
 

	// Check for directory existence 

	file_exists($directory) or die("$directory doesn't exist\n");

	$files = @scandir($directory) or die("$directory not a directory\n");
 

	// Check for contents (. and .. don't count)

	if(count($files)<=2)

		die("$directory is empty\n");

	if(count($files)<=12)

		die("$directory has less than 10 files, no need to delete any\n");
 

	// Get creation dates (filemtime() for modification date)

	foreach($files as $file){

		if($file != "." && $file != "..")

			$filectimes[] = filectime($directory.$file).$file;

	}
 

	// Sort ascending by date

	sort($filectimes);
 

	// Loop until 10 remain

	$i = count($filectimes)-1;

	do {

		echo "Deleting (unlinking) ".$directory.substr($filectimes[$i],10).", creation date was ".date("Y-m-d H:i:s",substr($filectimes[$i],0,10))."\n";

		unlink($directory.substr($filectimes[$i],10) or die("Couldn't delete file ".$directory.substr($filectimes[$i],10)."\n");

		$i--;

	} while ($i>10);
 

	return 1;

}
 

deleteOldFiles("cam3/");

Open in new window

0
 

Author Comment

by:arvid_kristiansen
ID: 22867786
Absx-
Sorry, but when I ad your code to the existing code the browser window shows nothing (white) and no files get deleted. Any clues?
0
 
LVL 9

Expert Comment

by:absx
ID: 22873832
Hi,

The errors might have been set to not be shown. You can turn on error reporting by adding the line

set_error_reporting("E_ALL");

in the beginning of the script.

Also, you can save the script from my last post in it's own file (say, test.php) and open this in your browser for testing.
0
 

Author Comment

by:arvid_kristiansen
ID: 22876314
Hi, still no result. I get the following error report; Parse error: syntax error, unexpected ';' in /customers/arvidkristiansen.com/arvidkristiansen.com/httpd.www/cam3/test.php on line 27

I have tryed to remove the ; in line 27 but without result.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 9

Expert Comment

by:absx
ID: 22876758
Ah!

The error's on the only line I didn't test with (didn't really want to delete stuff from my test directory. The line 27 is missing a closing parenthesis, fixed below:
unlink($directory.substr($filectimes[$i],10) or die("Couldn't delete file ".$directory.substr($filectimes[$i],10)."\n");
 

Should be
 

unlink($directory.substr($filectimes[$i],10)) or die("Couldn't delete file ".$directory.substr($filectimes[$i],10)."\n");

Open in new window

0
 

Author Comment

by:arvid_kristiansen
ID: 22877511
OK, the code is in its own file ( test.php ) and does not generate any errors, BUT it does not do any thing!
0
 

Author Comment

by:arvid_kristiansen
ID: 22879297
I tryed to inclued it in my index.php file also, but it had no effect there iver.
Allso, please keep in mind that it is only .jpg files I want to delete.
0
 
LVL 13

Expert Comment

by:Xyptilon2
ID: 22879356
Here you go, sorted by time, change the folder to your own and call from PHP, call this file test.bash and CHMOD it to 755

#!/bin/bash
 
num_files='ls -1tr /home/folder/files/*.jpg | wc -l'
num_to_delete='expr ${num_files} - 10'
if [ ${num_to_delete} -gt 0 ]; then
for i in 'ls -1tr /home/folder/files/*.jpg | head -n ${num_to_delete}'; do
rm $i
done
fi

Then from PHP do

<?PHP
$sOutput = `./test.bash 2&>1`;
echo $sOutput;
?>

Note that this is not a quote `` but a backtick operator.
Note that 2&>1 redirects STDERR to STDOUT so you can capture error messages. Goodluck!
0
 

Author Comment

by:arvid_kristiansen
ID: 22879965
Xyptilon2:

I get the following error; Warning: shell_exec() [function.shell-exec]: Cannot execute using backquotes in Safe Mode in /customers/arvidkristiansen.com/arvidkristiansen.com/httpd.www/cam3/test1.php on line 2

What do yoy meen with this; CHMOD it to 755?
0
 
LVL 13

Expert Comment

by:Xyptilon2
ID: 22880017
The error message means that safe mode is set to ON with your hosting provider prohibiting you from executing shell commands in this way. If they cannot change this setting im afraid you're going to have to look for a php only solution.

CHMOD 755 means set the permissions of the file to 755, which is an octal value and means RWX for owner RX for group and RX for world, where R stands for read, W for write and X for Execute.
0
 
LVL 9

Accepted Solution

by:
absx earned 500 total points
ID: 22883620
Hi,

I'm rather sure there's a permission problem of some kind. You can change the file and directory permissions through most FTP / SCP clients. I'm posting one more version of the script before, which I've duly tested to work if the permissions are correct (and it should tell you if they're not).

I've also attached images of a successful operation, where I intentionally had some files in read-only permission (different in Windows than Unixes, but should look the same for PHP).
<?

function deleteOldFiles($directory,$type = "") {
 

	// Check for directory existence 

	file_exists($directory) or die("Directory $directory doesn't exist<br />\n");

	$files = @scandir($directory) or die("Not a directory: $directory<br />\n");
 

	// Get creation dates and filter for type (filemtime() for modification date)

	foreach($files as $file){

		if(!empty($type) && strtolower(substr($file,-3,3)) == strtolower($type))

			$filectimes[] = filectime($directory.$file).$file;

		elseif(empty($type) && !in_array($file,array(".","..")))

			$filectimes[] = filectime($directory.$file).$file;

	}
 

	// Abort if less than ten matches

	if(count($filectimes)<=10){

		if(!empty($type)) $typedesc = " of type \"$type\"";

		else $typedesc = "";

		die("Directory $directory has 10 or less files$typedesc, no need to delete any<br />\n");

	}
 

	// Sort ascending by date

	sort($filectimes);
 

	// Loop until 10 remain

	$i = 0;

	do {

		if(@unlink($directory.substr($filectimes[$i],10)))

			echo "File ".$directory.substr($filectimes[$i],10).", successfully deleted.<br />\n";		

		else

			echo "Couldn't delete file ".$directory.substr($filectimes[$i],10).". Permission problem?<br />\n";		

		$i++;

	} while ($i<count($filectimes)-10);

}
 

deleteOldFiles("d:/foo/test/","jpg");

?>

Open in new window

directory-before.jpg
directory-after.jpg
browser-output.jpg
0
 

Author Comment

by:arvid_kristiansen
ID: 22904780
ABSX-
I have taken your new script to my index.php and now I get the following error; Directory arvidkristiansen.com/cam3/ doesn't exist. (The page is normal otherwise).
I have all my photos in a folder called "cam3". This folder is in the root of my domain "www.arvidkristiansen.com" What could be wrong?
0
 
LVL 9

Expert Comment

by:absx
ID: 22905418
Hi Arvid,

It would seem you're trying to refer to the directory with the URL rather than the file system path. If you take the domain name off the directory specification, it should work.

As in
deleteOldFiles("cam3/","jpg");

rather than
deleteOldFiles("arvidkristiansen.com/cam3/","jpg");
0
 

Author Comment

by:arvid_kristiansen
ID: 22905533
After playing around alot I finaly got it to work THANK YOU EVERY ONE, spesialy ABSX.

The correct path for my files needed to be something like this;
"File /customers/arvidkristiansen.com/arvidkristiansen.com/httpd.www/cam3/08103113022500.jpg, successfully deleted."

The result of my effort can be seen here; http://www.arvidkristiansen.com/web/index.htm
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now