include all directory files in class - php

I have a php file like this
class Config {
public static $__routes = array(
"Home" => "index.php",
"Support" => "support.php",
);
}
Config::__routes += (include 'config/example1.php');
Config::__routes += (include 'config/example2.php');
can I include a directory
for example:
include('include 'config/example1.php');
include('include 'config/example2.php');
will be something like:
include('config/*');

You can use glob try:
foreach (glob('config/*.php') as $file)
include( $file );

This code will include all .php files in a given folder.
<?php
if ($handle = opendir('/path/to/includes/folder')) {
while (false !== ($entry = readdir($handle))) {
$path_parts = pathinfo($entry);
if ($path_parts['extension'] == '.php') include $entry;
}
closedir($handle);
}
?>
explanation:
opendir will open the given folder and return handle of folder.
while loop will loop through all files in that folder.
pathinfo will create an array include file information which one of then is extension of file.
Then we compare extension of found file to .php, if it was php file, we include it.
Then we close the handle of opened folder.

Related

How to set the path in opendir() in an included file?

In my application root folder I have a folder named 'articles' in which there are some files. And in my root folder I have the header file and some other files. The same header file is used in the files inside the articles directory too.
In my header file, I have a dropdown menu which lists the files inside the articles directory. And I have used the following code.
<?php
$dir = "./articles";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && $entry != "images" && $entry != "index.php") {
$foo = $entry;
$foo = str_replace("_", " ", $foo);
$foo = str_replace(".php", "", $foo);
$foo = ucwords($foo);
?>
<a class="dropdown-content-a" href="<?php echo "$entry" ?>"><?php echo $foo ?></a>
<?php
}
}
closedir($handle);
}
?>
This works fine in the files in the root folder but it does not work in the files in the 'articles' folder(But the header file is still in the root folder and relative to the header file, the path './articles' is correct).
How to overcome this by using the same header file?
use (..) to cd the previous directory
include_once(dirname(__FILE__).'/../filename.php');
Maybe you can try a condition-wise solution. Check the path and decide to use ".." or not.

How to echo out the contents of every text file that in a directory?

I have created a directory with some files in there:
index.php
one.txt
two.txt
three.txt
four.txt
In the index.php page, I am currently using this code to echo out all of the files within the directory:
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>
Now, if anyone views the index.php page, this is what they'll see:
one.txt two.txt three.txt four.txt
As you can see from the PHP code, index.php is blacklisted so it is not echoed out.
However, I would like to go a step further than this and echo out the contents of each text file rather than the filenames. With the new PHP code (that I need help with creating), whenever someone visits the index.php page, this is what they'll now see:
(Please ignore what is in the asterisks, they are not a part of the code, they just indicate what each text file contains)
Hello ** this is what the file **one.txt** contains **
ok ** this is what the file **two.txt** contains **
goodbye ** this is what the file **three.txt** contains **
text ** this is what the file **four.txt** contains **
Overall:
I would like to echo out the contents of every file in the directory (they are all text files) aside from index.php.
You could use file_get_contents to put the file into a string.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry " . file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
Furthermore, you could use PHP's glob function to filter only the .txt files out, that way you do not have to blacklist files if you're going to be adding more files to that directory that need ignored.
Here is how it would be done using the glob function.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename " . file_get_contents($filename) . "\n";
}
?>
This would print the contents of the files. You can do some workaround if the path is not the current path and writing some kind of boundary between the files contents.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
I hope this helps you.
Never reinvent the wheel. Use composer.
Require symfony/finder
use Symfony\Component\Finder\Finder;
class Foo
{
public function getTextFileContents($dir)
{
$finder = (new Finder())->files()->name('*.txt');
foreach ($finder->in($dir) as $file) {
$contents = $file->getContents();
// do something while file contents...
}
}
}
I would give a chance to some SPL filesystem iterators to accomplish such this task:
$dir = '/home/mydirectory';
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
$rdi = new \RegexIterator($rdi, '/\.txt$/i');
$iterator = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $file) {
echo 'Contents of the '.$file->getPathname().' is: ';
echo file_get_contents($file->getPathname());
}
This will recursively find & iterate all .txt files in given directory, including sub-directories.
Since each $file in iteration is a FilesystemIterator instance, you can use all related methods for additional controls like $file->isLink() (true for symbolic links), $file->isReadable() (false for unreadable files) etc..
If you don't want lookup sub-folders, just change the RecursiveDirectoryIterator in the second line from:
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
to:
$rdi = new \DirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
Hope it helps.
As #brock-b said, you could use glob to get the full list of files and file_get_contents to grab the contents:
$blacklist = array('index.php');
$files = glob('*.txt'); # could be *.* if needed
foreach ($files as $file) {
if (!in_array(basename($file), $blacklist)) {
echo file_get_contents($file);
}
}
Note: the blacklist wont be hit since you're seeking for *.txt files. Only useful when doing an *.* or *.php file search

Get files names inside a directory path

Is there any PHP function to retrieve the file/s name/s inside a directory path?
E.g., I have a CSS file inside /css, and I want to get this file's name.
Solution:
As #ShankarDamodaran suggested, I used:
//Get CSS file/s name/s
chdir($_SERVER['DOCUMENT_ROOT'] . '/css'); //<--- Set the directory here...
foreach (glob("*.css") as $filename) { //<----Get only CSS files
$CSSfiles[] = $filename;
}
This will return an array ($CSSfiles) with the names of the CSS files.
Make use of glob() for this
<?php
chdir('../css'); //<--- Set the directory here...
foreach (glob("*.*") as $filename) { //<--- Pass *.css , (If you need just the CSS files)
echo $filename."<br>";
}
<pre>
<?php
if ($handle = opendir('css')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
}
closedir($handle);
?>
</pre>
USE
<?PHP echo realpath('YOURFILE.PHP');?>
CHECK HERE

Scan files in a directory and sub-directory and store their path in array using php

I want not scan all the files in a directory and its sub-directory. And get their path in an array. Like path to the file in the directory in array will be just
path -> text.txt
while the path to a file in sub-directory will be
somedirectory/text.txt
I am able to scan single directory, but it returns all the files and sub-directories without any ways to differentiate.
if ($handle = opendir('fonts/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry<br/>";
}
closedir($handle);
}
What is the best way to get all the files in the directory and sub-directory with its path?
Using the DirectoryIterator from SPL is probably the best way to do it:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."\n";
$file is an SPLFileInfo-object. Its __toString() method will give you the filename, but there are several other methods that are useful as well!
For more information see: http://www.php.net/manual/en/class.recursivedirectoryiterator.php
Use is_file() and is_dir():
function getDirContents($dir)
{
$handle = opendir($dir);
if ( !$handle ) return array();
$contents = array();
while ( $entry = readdir($handle) )
{
if ( $entry=='.' || $entry=='..' ) continue;
$entry = $dir.DIRECTORY_SEPARATOR.$entry;
if ( is_file($entry) )
{
$contents[] = $entry;
}
else if ( is_dir($entry) )
{
$contents = array_merge($contents, getDirContents($entry));
}
}
closedir($handle);
return $contents;
}

delete folder with all content with php

I have main folder named "gallery". In this folder there are some sub folders like "animal", "tree", etc. folder "animal" contains some pictures and so on. suppose i want to delete "animal" folder with all pictures in it, how can do this?
i tried-
rmdirr($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
but in server, it deleted the whole "gallery" folder with all in it. please tell me what i am doing wrong and also give me a solution. thanks in advance.
If there are no subfolders you can use glob() to empty the directory before using rmdir():
foreach( glob( "/path/to/dir/*.*" ) as $filename ) {
unlink( $filename );
}
rmdir( "/path/to/dir" );
By the way, rmdir() shouldn't delete any files. It just fails if the directory isn't empty. You might want to make sure there's nothing else in your code that causes the parent directory to be wiped out.
Just delete the directory recursively with a helper function:
rrmdir($_SERVER['DOCUMENT_ROOT']."admin/gallery/animal");
function rrmdir($path)
{
return is_file($path)
? #unlink($path)
: array_map('rrmdir', glob($path.'/*')) == #rmdir($path)
;
}
When removing a desired directory, you must first remove the files within that directory. Once that is complete, then you may remove the directory -- assuming you have the proper permissions.
Included below is code that removes the files in the directory and will then remove the specified directory itself:
<?php
$dirname = "animal";
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("Unable to delete $dir$file");
}else{
unlink($dir.$file) or DIE("Unable to delete $dir$file");
}
}
}
closedir($mydir);
}
destroyDir($dirname);
?>

Categories