Improve Session GC for files driver

Close #3701
diff --git a/system/libraries/Session/drivers/Session_files_driver.php b/system/libraries/Session/drivers/Session_files_driver.php
index 74528e9..45da91c 100644
--- a/system/libraries/Session/drivers/Session_files_driver.php
+++ b/system/libraries/Session/drivers/Session_files_driver.php
@@ -326,7 +326,7 @@
 	 */
 	public function gc($maxlifetime)
 	{
-		if ( ! is_dir($this->_config['save_path']) OR ($files = scandir($this->_config['save_path'])) === FALSE)
+		if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
 		{
 			log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
 			return FALSE;
@@ -340,7 +340,7 @@
 			($this->_config['match_ip'] === TRUE ? 72 : 40)
 		);
 
-		foreach ($files as $file)
+		while (($file = readdir($directory)) !== FALSE)
 		{
 			// If the filename doesn't match this pattern, it's either not a session file or is not ours
 			if ( ! preg_match($pattern, $file)
@@ -354,6 +354,8 @@
 			unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
 		}
 
+		closedir($directory);
+
 		return TRUE;
 	}