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);
?>
Related
I'm using php dir() function to get files from directory and loop through it.
$d = dir('path');
while($file = $d->read()) {
/* code here */
}
But this returns false and gives
Call to member function read() on null
But that directory exists and files are there.
Also, Is there any alternative to my above code?
try to use this :
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);
}
source :
http://php.net/manual/en/function.readdir.php
You can try this:
$dir = new DirectoryIterator(dirname('path'));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
Source: PHP script to loop through all of the files in a directory?
If you take a look into documentation you will see:
Returns an instance of Directory, or NULL with wrong parameters, or
FALSE in case of another error.
So Call to member function read() on null means that you got an error (I think that this failed to open dir: No such file or directory in...).
You can use file_exists and is_dir for checking if the given path is a directory and if it really exists.
Example:
<?php
...
if (file_exists($path) && is_dir($path)) {
$d = dir($path);
while($file = $d->read()) {
/* code here */
}
}
Please check your file path if your path is right. Then please try this code this may help you. Thanks
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
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
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
I am trying to write a php function to save and then display comments on an article.
In my save.php, I am formulating the file with:
$file = "article1/comments/file".time().".txt";
Then using fwrite() to write to a directory.
In my index I have:
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files = array($file);
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments/'.$comments);
echo "</div>";
}
}
}
closedir($handle);
}
For the most part this displays the comments in the correct order, but for some reason, some files are displaying out of order. Furthermore, if I change sort() to rsort(), there is no change in how they are displayed.
I presume this is because readfile() is not following the sorted array's order. So I am wondering for one, why readfile does not display the files in order from newest to oldest, and two, how can I make it display them correctly?
Thanks.
edit: I copied the directory of comments from the live site to my local xampp installation, and the comments are displayed in order locally, but using the same code on my site results in comments not being in order.
Take a look at DirectoryIterator, make sure to check 1st comment for DirectoryIterator's isFile() method, it should be enough to solve this question.
Try this:
$files = array();
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[] = $file; //adding file to array
}
}
closedir($handle);
}
//if array is not empty-check (can go here)
if(count($files)>0) {
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments'.$comments);
echo "</div>";
}//~foreach
}//~if
Please, use any database for this stuff! Don't use files! This is not realy secure and has low performance
I have this script and when i try to run it, it just says waiting for localhost and never actually runs. If i go to my localhost i can run other files with no problem.
What's wrong with this script?
<?php
$dir = 'Images/uploaded/';
if($handle = opendir($dir)) {
$file = readdir($handle);
while($file !== false) {
echo "<li><img class=\"thumb\" src=\"".$dir.$file."\" /></li>";
}
}
closedir($handle);
?>
You're not modifying $file inside the loop. $file never changes, and therefore you have an infinite loop.
From http://php.net/readdir:
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
You need to call readdir() within the loop.