I have the next code but i need scan multiple dir on array.
public static function scanFiles($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
Your use is: scanFiles('path/to/folder')
But I need the path to be an array, example: scanFiles(array('path/to/folder1', 'path/to/folder2')).
Some one help...?
Thank you in advance and sorry for my bad english.
you can change the function like this, just adding foreach with the code block that you have for scanning directory
public static function scanFiles($directories, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
foreach($directories as $directory) {
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if ($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if ($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if ($listDirs) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if ($listFiles) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
}
return $arrayItems;
}
Related
I have this code. The idea with it, is that i reads a big(very big: 300mb) JSON file, line by line and set the JSON data into an SQL table. But the same line of JSON data gets inserted more than once, and after the PHP script has been through all lines, it just starts over.
There is 200268 objects in the JSON file, seperated in lines
Here is my code:
example.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
include("config-sample.php");
include("include.classloader.php");
$classLoader->addToClasspath(ROOT);
$mysql = new MySQLConn(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASS);
$db = new JSONtoMYSQL($mysql);
$handle = fopen("programoversigter.json", "r");
if ($handle) {
while (($linne = fgets($handle)) !== false) {
$db->save(json_decode($linne)->_source, "igen");
print($iasd . " ");
$iasd = $iasd++;
}
fclose($handle);
} else {
echo "assscsad";
}
die();
?>
include.classloader.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
class ClassLoader{
protected $classpath;
public function __construct(){
$this->classpath = array();
}
public function addToClasspath($dir){
if(is_dir($dir)){
$this->classpath[] = $dir;
}else{
throw new Exception("cannot find directory: $dir");
}
}
public function load($classname){
$ok = false;
for($i=0;$i<count($this->classpath);$i++){
$path = $this->classpath[$i];
/* echo "load recur \"" . $path . "\";//<br>\n"; */
$ok = $ok || $this->load_recursive($path, $classname);
}
return $ok;
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$ret = $ret || $this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
public function loadTestFiles(GroupTest $g){
foreach($this->classpath as $c){
$this->loadTestFilesHelper($g, $c);
}
}
protected function loadTestFilesHelper(GroupTest $g, $classpath){
$theList = array();
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->loadTestFilesHelper($g, $classpath . $file . "/");
}else{
if(strpos($file, "test.class.") === 0 &&
strpos($file, ".php") == strlen($file)-4){
$g->addTestFile($classpath . $file);
}
}
}
}
closedir($handle);
unset($handle);
}
}
}
class ClassLoaderToString extends ClassLoader{
public function __construct(){
parent::__construct();
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
protected function printClass($classpath, $file){
if(strpos($classpath, ROOT) === 0){
$classpath = substr($classpath, strlen(ROOT));
echo "include_once(ROOT . \"" . $classpath . $file . "\");\n";
}else{
echo "include_once(\"" . $classpath . $file . "\");\n";
}
}
}
function milestone_autoload($classname){
global $classLoader;
// global $control;
// $str = "classname: ";
// $str .= $classname;
// $str .= "\n";
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
try{
$ok = $classLoader->load($classname);
// $str .= ":" . $ok;
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
}catch(Exception $e){
$model->getLogger()->log($model, ALogger::$HIGH, print_r($e, true));
}
}
spl_autoload_register('milestone_autoload');
$classLoader = new ClassLoader();
?>
I am writing a function to recursively copy a specific file type from one folder to the other, but the function copies all the files in the folder.
function recurse_copy($src, $dst) {
$dir = opendir($src);
#mkdir($dst);
while (false !== ( $file = readdir($dir))) {
if (( $file != '.' ) && ( $file != '..' )) {
if (is_dir($src . '/' . $file)) {
if ($file->getExtension() == "pdf") {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
}
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
} closedir($dir);
}
// if statements for
$itp = new RecursiveDirectoryIterator("foldername/", > FilesystemIterator::SKIP_DOTS);
$displayp = Array('pdf');
$i = 0;
foreach (new RecursiveIteratorIterator($itp) as $filepop) {
if (in_array(strtolower(array_pop(explode('.', $filepop))), $displayp))
if ($filepop->getExtension() == "pdf") {
echo >
recurse_copy("a", "b");
}
}
$itcopy = new RecursiveDirectoryIterator("foldername/", FilesystemIterator::SKIP_DOTS);
$displayp = Array ( 'pdf' );
foreach(new RecursiveIteratorIterator($itcopy) as $filecopy)
{
if (in_array(strtolower(array_pop(explode('.', $filecopy))), $displayp))
if ($filecopy->getExtension()=="pdf"){
copy($filecopy->getrealPath(),'pdf_folder/'.$filecopy->getFilename()) ;
}
}
I would like to ask what I have to add to make this function to show not only the files on top dir but also the files in subdirs..
private function _populateFileList()
{
$dir_handle = opendir($this->_files_dir);
if (! $dir_handle)
{
return false;
}
while (($file = readdir($dir_handle)) !== false)
{
if (in_array($file, $this->_hidden_files))
{
continue;
}
if (filetype($this->_files_dir . '/' . $file) == 'file')
{
$this->_file_list[] = $file;
}
}
closedir($dir_handle);
return true;
}
Thank you in advance!
You could implement the recursion yourself, or you could use the existing iterator classes to handle the recursion and filesystem traversal for you:
$dirIterator = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$recursiveIterator = new RecursiveIteratorIterator($dirIterator);
$filterIterator = new CallbackFilterIterator($recursiveIterator, function ($file) {
// adjust as needed
static $badFiles = ['foo', 'bar', 'baz'];
return !in_array($file, $badFiles);
});
$files = iterator_to_array($filterIterator);
var_dump($files);
By this you can get all subdir content
customerdel('FolderPath');
function customerdel($dirname=null){
if($dirname!=null){
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
echo $dirname."/".$file.'<br>';
else{
echo $dirname.'/'.$file.'<br> ';
customerdel($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
}
Here is how you can get a recursive array of all files in a directory and its subdirectories.
The returned array is like: array( [fileName] => [filePath] )
EDIT: I've included a small check if there are filenames in the subdirectories with the same name. If so, an underscore and counter is added to the key-name in the returned array:
array( [fileName]_[COUNTER] => [filePath] )
private function getFileList($directory) {
$fileList = array();
$handle = opendir($directory);
if ($handle) {
while ($entry = readdir($handle)) {
if ($entry !== '.' and $entry !== '..') {
if (is_dir($directory . $entry)) {
$fileList = array_merge($fileList, $this->getFileList($directory . $entry . '/'));
} else {
$i = 0;
$_entry = $entry;
// Check if filename is allready in use
while (array_key_exists($_entry, $fileList)) {
$i++;
$_entry = $entry . "_$i";
}
$fileList[$_entry] = $directory . $entry;
}
}
}
closedir($handle);
}
return $fileList;
}
I've got the problem of trying to display two albums of photos from a db using php. Currently the following code works but for just one album. Basically I need it to display photos from 'mount-everest-part-2' aswell.
<?php
$path = "images/galleries/";
$album = 'mount-everest-part-1';
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach($files as $file) {
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
?>
How can I use this code to open two files and spit the files out using the same foreach loop?
This sounds like one of those things that OOP would suit nicely. Here's an example:
<?php
class Album_Picture_File {
private $fileName;
private $path;
private $album;
public function __construct($fileName, $path, $album) {
$this->fileName = $fileName;
$this->path = $path;
$this->album = $album;
}
private function getAlbumPath() {
return '../' . $this->path . $this->album;
}
public function getPicturePath() {
return $this->getAlbumPath() . '/images/' . $this->fileName;
}
public function getThumbnailPath() {
return $this->getAlbumPath() . '/thumbs/' . $this->fileName;
}
}
function fetchFiles($path, $album) {
$files = array();
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$fullPath = $path . $album . '/thumbs/' . $file;
$files[$fullPath] = new Album_Picture_File($file, $path, $album);
}
}
closedir($handle);
}
ksort($files); //sort after key (out file path)
return $files;
}
$files = array_merge(
fetchFiles('images/galleries/', 'mount-everest-part-1'),
fetchFiles('images/galleries/', 'mount-everest-part-2')
);
foreach($files as $file) {
echo '<li><img src="' . $file->getThumbnailPath() . '" /></li>';
}
?>
Note that instead of pushing $files with strings, we push it with Album_Picture_File objects.
Create a global array :
$all = array();
Then, make 2 loops and push the global array (create a function that reads the directory for example)
$files_dir_one = getFiles("your_dir");
$files_dir_two = getFiles("your_dir2");
$all = array_merge($files_dir_one, $files_dir_two);
function getFiles($directory) {
$files = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
//asort($files);
return $files;
}
And then, the last step : populate the view
How can I use this code to open two files and spit the files out using the same foreach loop?
Taking your question literally it works like this. First of all extract a function with the two input variables:
/**
* #param string $path
* #param string $album
*/
function list_images($path, $album) {
$files = [];
if ($handle = opendir($path . $album . '/thumbs/'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._')
{
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach ($files as $file)
{
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
}
Then you can just iterate over your two albums and output both:
$path = "images/galleries/";
$albums = ['mount-everest-part-1', 'mount-everest-part-2'];
foreach ($albums as $album)
{
list_images($path, $album);
}
The main issue it's still the same:
This is my proyect
/
| index.php
|-test1
| test.php
The test.php
<?php
echo $variable;
?>
The index.php
<?php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php");
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
And it's works like a charm, the output is:
test
index
If i want to encapsulate this functionality in a function like this:
index1.php
$variable = "<br>index";
echo 'test<br>';
$full_path = dirname(__FILE__)."/test1";
$adm_extension = array( "php" );
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
require $item_path;
}
}
}
}
}
}
rTest($full_path, $adm_extension);
I got this:
( ! ) Notice: Undefined variable: variable in C:\wamp\www\sandbox\test1\test.php on line 3
Any clue??
your script probably, when going through files, opens test.php before index1.php so $variable isn't defined yet
test it:
function rTest($full_path, $adm_extension){
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
echo $item_path.'<br />';
require $item_path;
}
}
}
}
}
}
Ok, a friend help me to solve it out.
It's was a really dumb error. The problem was when I made the require, it was made in the function scope.
For my solution I do something like this:
function rTest($full_path, $adm_extension){
$paths = array();
if (is_dir($full_path)) {
if (($handle = opendir($full_path))) {
while ($file = readdir($handle)) {
if (is_file($full_path . '/' . $file)) {
$item_path = $full_path . '/' . $file;
$extension = pathinfo($item_path, PATHINFO_EXTENSION);
if (in_array($extension, $adm_extension)) {
$paths[] = $item_path;
}
}
}
}
}
return $paths;
}
foreach(rTest($full_path, $adm_extension) as $path){
require $path;
}