php is erasing all files not only *.dat

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
methos
Forum Newbie
Posts: 13
Joined: Sat Oct 21, 2006 8:31 am

php is erasing all files not only *.dat

Post by methos »

Why does this code not only erases all .dat files but also all the files under that directory such as a file called "empty" (with no file extension)? ($sessionid is created using random md5) I only want it to erase all .dat files.

Code: Select all

// destroy previous sessions
$sessionfilename = ".$sessionid.".dat;
  foreach (glob("./sessions/*") as $sessionfilename) {
   if (filemtime($sessionfilename) + 604800 < time()) {
     unlink($sessionfilename);
   }
  }
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Re: php is erasing all files not only *.dat

Post by timvw »

methos wrote:Why does this code not only erases all .dat files but also all the files under that directory such as a file called "empty" (with no file extension)? ($sessionid is created using random md5) I only want it to erase all .dat files.

Code: Select all

// destroy previous sessions
$sessionfilename = ".$sessionid.".dat;
  foreach (glob("./sessions/*") as $sessionfilename) {
   if (filemtime($sessionfilename) + 604800 < time()) {
     unlink($sessionfilename);
   }
  }
You are globbing over ./session/* -> and each file that is found is stored in $sessionfilename in the foreach construct.... and then you unlink $sessionfilename...

Code: Select all

foreach(glob("xxx/*.dat") as $foundfile) { echo $foundfile; }
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

Also, I could be crazy..... but shouldn't this be:

Code: Select all

$sessionfilename = $sessionid.".dat";
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Nah, you're not crazy. That's a syntax error and you corrected it. :)
Post Reply