Re: how to select files from a directory and transfer to a different dir ?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Vaibhav Sibal wrote:
> I need to select around 200 files at random out of a file pool of
> 10k-15k files from a directory and then transfer them to another
> directory on my linux server which runs Apache 2.0.52, PHP 5.0.3 and
> Mysql. I will also be requiring to add the paths of all those files
> into a database. If someone can please suggest the way to do it, I
> will be really grateful. I dont know how to select 200 files at random
> and then transferring the files to another directory and then adding
> those files to a database.

<?php
  $quota = 200;
  $path = "/path/to/massive/directory/";
  $userdir = "/home/username/";
  $dir = opendir($path) or die("Can't read directory $path");
  //Do you REALLY need them to be selected randomly?
  //That's gonna be a pain...
  //Not to code, just very long time to read all 10,000 entries...
  //You'd be WAY better off to just assign the first 200 to the person...
  //Oh well.
  //Your problem, not mine.
  $files = array();
  while ($file = readdir($dir)){
    if ($file != '.' && $file != '..'){
      $files[] = $file;
    }
  }
  $selected = array();
  //Just in case there are not 200 files available, compare to count($files)
  while (count($selected) < $quote && count($selected) < count($files)){
    $rand = mt_rand(0, count($files)); //maybe count($files) - 1 is right.
    $file = $files[$rand];
    unset($files[$rand]); //Take it out of our random pool.
    $selected[] = $file;
  }
  reset($selected);
  while (list(, $file) = each($selected)){
    //You MAY not be able to use rename() across a Unix/Samba directory.
    //If not, you have to use:
    //exec("mv $path/$file $userdir/$file", $result, $error);
    //if ($error) print("OS Error: $error\n" . implode("", $result));
    //That will be even slower than this:
    rename("$dir/$file", "$userdir/$file");
    //Shove the assignment into your database, so Supervisor can
    //crack the whip:
    $query = "insert into assigned (file, user, whatdate) ";
    $query .= " values('$file', '$userdir', now()) ";
    mysql_query($query) or print("Could not record assignement of $file to
$userdir at " . date('m/d/Y h:i:s a'));
  }
?>

WARNING:
You will have to make sure this script never runs TWO copies at once.

If you run two at once, sooner or later, you'll get all screwed up...

It could be re-written, in various ways, to avoid that problem, if you
need it...

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux