Get files names inside a directory path - php

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

Related

How to check if a folder has sub folders using glob?

I have a dir TestRoot with two folder: TestFolderA, which has another folder and two files, and TestFolderB which only has one file. I am trying to check whether these folders themselves contain more folders.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
</head>
<body class="stretched">
<?php
$root = "docs/RootTest";
$files = scandir($root);
foreach($files as $file)
{
if ($file != '.' && $file != '..')
{
$link = $root.'//'.$file;
if(is_dir($link)) //Check if file is a folder
{
$folders = glob($link."/", GLOB_ONLYDIR);
if(count($folders)>0) //Check if it contains more folders
{
echo $link." ";
echo "Has Sub-folders ";
}
else
{
echo $link." ";
echo "None ";
}
}
}
}
?>
</body>
</html>
When I run this code the output is "docs/RootTest//TestFolderA Has Sub-folders" which is correct however I also get the output "docs/RootTest//TestFolderB Has Sub-folders" which is not correct. What am I doing wrong?
$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
You can also try glob() followed GLOB_ONLYDIR option
Change line
$folders = glob($link."/", GLOB_ONLYDIR);
to
$folders = glob($link."/*", GLOB_ONLYDIR);
Just added "*"
OK albeit not the way I wanted to, but after glob for some reason refuses to behave as expected I I instead opted to just scan the directory again and sorted it so that folders are first in the array. Then I just checked if the first element is a directory.
if(is_dir($link))
{
$folders = scandir($link, 1);
if(is_dir($link.'/'.$folders[0]))
{
echo $link." ";
echo "Has Sub-folders ";
}
PHP is_dir() Function
The is_dir() function checks whether the specified file is a directory.
This function returns TRUE if the directory exists.
<?php
$file = "images";
if(is_dir($file))
{
echo ("$file is a directory");
}
else
{
echo ("$file is not a directory");
}
?>
Output :
images is a directory

How can i read folder names?

i have a folder named categories which has lots of folder inside.I need to take those names and insert into database.
is there any function or way that takes folder names with php?
Just a simple RTM would have got you: readdir()
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
?>
Be sure to read the documentation for the gotchas!!!
You can get all folder name with this code
<?php
$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
?>

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

delete file called ".html"

I accidentally created a file with no name http://website.com/myFolder/.html,
now, in the control panel of my webhost, this file is not listed, I cannot see or delete it...
but I can see it using this "myList.php" file: (http://website.com/myFolder/myList.php):
<?php
echo "<ol>";
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<li>'.$entry.'</li>';
}
}
closedir($handle);
}
echo "</ol>";
?>
This "myList.php" file outputs all the files present in the directory: http://website.com/folder/
also the file with no name http://website.com/myFolder/.html
How can I delete this file?
I tried to create another .php file called http://website.com/myFolder/myDelete.php,
and use the php function unlink():
<?php
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
echo ("Error deleting".$path);
}else{
echo ("Deleted".$path);
}
}
}
?>
But it doesn't work.
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
^^^^^----undefined variable
Why all of that when you could just have
unlink('.html');
? Your unwanted file is in the same directory as your myDelete.php script, so the rest of all that is pointless.
Files and directories that begin with . are considered "hidden" on *nix systems. You can see them with ls -la but not with just ls.
Try changing the $file variable to just be the name of the file ".html". Make sure to use the $file variable for the delete - this is not defined in your example.
$file = ".html";
if ( file_exists( $file ) ){
if ( ! unlink( $file ) ){
echo "Error deleting '$file'" );
} else{
echo "Deleted '$file'";
}
} else {
echo "File '$file' does not exist!";
}
The one comment suggested you use FTP, you should have FTP access to your server then you can simply delete through FTP.

Read File Names From folder Only Keep Files with .iso extention

I have a script that gets a string from a config file and based on that string grabs the file names of a folder.
I now only need the iso files. Not sure if the best way is to check for the .iso string or is there another method?
<?php
// Grab the contents of the "current.conf" file, removing any linebreaks.
$dirPath = trim(file_get_contents('current.conf')).'/';
$fileList = scandir($dirPath);
if(is_array($fileList)) {
foreach($fileList as $file) {
//could replace the below if statement to only proceed if the .iso string is present. But I am worried there could be issues with this.
if ($file != "." and $file != ".." and $file != "index.php")
{
echo "<br/><a href='". $dirPath.$file."'>" .$file."</a>\n";
}
}
}
else echo $dirPath.' cound not be scanned.';
?>
If you only need the files with an extension of .iso, then why not use:
glob($dirPath.'/*.iso');
rather than scandir()
try this:
if(is_array($fileList)) {
foreach($fileList as $file) {
$fileSplode = explode('.',$file); //split by '.'
//this means that u now have an array with the 1st element being the
//filename and the 2nd being the extension
echo (isset($fileSplode[1]) && $fileSplode[1]=='iso')?
"<br/><a href='". $dirPath.$file."'>" .$file."</a>\n":'');
}
}
If you want it in an OOP style you could use:
<?php
foreach (new DirectoryIterator($dirPath) as $fileInfo) {
if($fileInfo->getExtension() == 'iso') {
// do something with it
}
}
?>

Categories