linking directories and files in php - php

Hello stackoverflow community;
I'm trying to display a few files in a directory using php and coming unstuck:
In my file ('salad') I have three recipe files ('recipe1.txt', recipe2.txt, 'recipe3.txt') and I want to display them so I'm writing the following:
$script = opendir('salad');
while(false !==($file = readdir($script))) {
if (is_file($file)) {
echo "<p>$file</p>";
}
}
Unfortunately this only echos to the screen .DS_store, what am i doing wrong?

You could use this:
<?php
$dir = "/tmp"; // put what suits you here
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
echo"$files";
?>
source:
http://php.net/manual/en/function.scandir.php

Related

Require to display limited number of file names from directories -php

For the below code I have multiple directories and files. I can display one filename per directory(Which is good with the "BREAK").
<?php
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
break;
//---- if ($i>=5) { break; }
}
closedir($dh);
}
}
?>
With
if ($i>=5) { break; } I can still display 5 filenames but it reads only one directory.
I want to display at least 5 file names from all directories, how can I do it?
Use the scandir function.
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
or
If you are using unix you could also do a system call and run the following command.
ls /$dir | head -5
$dir is the directory and -5 is the number filenames in the directory.
Since you said that you have multiple directory's, I rewrote your code a bit:
(Here I first loop through all directory's with array_map() then I get all files from each directory with glob(). After this I just limit the files per directory with array_slice() and at the end I simply print all file names)
<?php
$directorys = ["images/", "xy/"];
$limit = 3;
//get all files
$files = array_map(function($v){
return glob("$v*.*");
}, $directorys);
//limit files per directory
$files = array_map(function($v)use($limit){
return array_slice($v, 0, $limit);
}, $files);
foreach($files as $directory) {
echo "<b>Directory</b><br>";
foreach($directory as $file)
echo "$file<br>";
echo "<br><br>";
}
?>
You don't have to break it, you can just skip it. And in doing so, you have to use continue instead.
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
}
closedir($dh);
}
}
Here is also another scenario. Because you mentioned that you have many directories but you only show one main directory, I am guessing that the directories you've mentioned were inside the /images/ directory.
$dir = "images/";
$i=1;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$j=1;
if (is_dir($file)) {
if ($internalDir = opendir($file)) {
while (($internalFile = readdir($internalDir)) !== false) {
echo $file."->filename: ".$internalFile."<br>";
if ($j>=5)
continue;
$j++;
}
closedir(opendir($file));
}
} else {
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
$i++;
}
}
closedir($dh);
}
}
Read more about continue here: http://php.net/manual/en/control-structures.continue.php

PHP auto-incude from a folder

I want to create a system which will include any .php file from a folder, similar to wordpress\plugins folder. Preferably drag and drop.
Any ideas how to do it?
Question is not clear...
read the folder files
scroll through the files found
if PHP - include it
<?php
function scandir2($dir)
{
$out = array();
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file == '.' or $file == '..') continue;
if (!is_dir($dir . '/'. $file))
{
$out[] = $dir . '/' . $file;
}
}
closedir($dh);
}
}
sort($out);
return $out;
}
$i=scandir2(".");
foreach($i as $name)
{
if(strstr($name ,'.php'))
include($name);
}
?>
this code scan directory and include php files ...
Here is the code to do that:
foreach (glob("/path/*.php") as $filename) {
include $file;
}
The glob() function returns an array of all .php files on the specified path.
Here is how I would do it...
<?php
$dirPath = '/path/to/files';
if ($handle = opendir($dirPath)) {
/* loop over files in directory */
while (false !== ($entry = readdir($handle))) {
/* find extension */
$ext = substr($entry,-3);
$ext = strtolower($ext);
/* include file if extension is PHP */
if ($ext === 'php') {
include_once($dirPath .'/'. $entry);
} //if
} //if
closedir($handle);
} //if
Note that there is several security concerns and possibly performance concerns.

Using php to rename all files in folder

new php programmer here. I have been trying to rename all the files in a folder by replacing the extension.
The code I'm using is from the answer to a similar question on SO.
if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($fileName, $newName);
}
closedir($handle);
}
I get no errors when running the code, but no changes are made to the filenames.
Any insight on why this isn't working? My permission settings should allow it.
Thanks in advance.
EDIT: I get a blank page when checking the return value of rename(), now trying something with glob() which might be a better option than opendir...?
EDIT 2: With the 2nd code snippet below, I can print the contents of $newfiles. So the array exists, but the str_replace + rename() snippet fails to change the filename.
$files = glob('testfolder/*');
foreach($files as $newfiles)
{
//This code doesn't work:
$change = str_replace('php','html',$newfiles);
rename($newfiles,$change);
// But printing $newfiles works fine
print_r($newfiles);
}
Here is the simple solution:
PHP Code:
// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
$file = realpath($filename);
rename($file, str_replace(".html",".php",$file));
}
Above code will convert all .html file in .php
You're probably working in the wrong directory. Make sure to prefix $fileName and $newName with the directory.
In particular, opendir and readdir don't communicate any information on the present working directory to rename. readdir only returns the file's name, not its path. So you're passing just the file name to rename.
Something like below should work better:
$directory = '/public_html/testfolder/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
Are you sure that
opendir($directory)
works? Have you checked that? Because it seems there might be some Document Root missing here...
I would try
$directory = $_SERVER['DOCUMENT_ROOT'].'public_html/testfolder/';
And then Telgin's solution:
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
That happens if the file is opened. Then php cannot do any changes to the file.
<?php
$directory = '/var/www/html/myvetrx/media/mydoc/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$dd = explode('.', $fileName);
$ss = str_replace('_','-',$dd[0]);
$newfile = strtolower($ss.'.'.$dd[1]);
rename($directory . $fileName, $directory.$newfile);
}
closedir($handle);
}
?>
Thank you so much for the suggestions. it's working for me!

How to get the file name under a folder?

Suppose I have a directory look like:
ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt
How can I use PHP to get these file names to an array, limited to a specific file extension and ignoring directories?
You can use the glob() function:
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Example 03: Using RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
if (strtolower(substr($file, -4)) == ".txt") {
echo $file;
}
}
?>
Try this:
if ($handle = opendir('.')) {
$files=array();
while (false !== ($file = readdir($handle))) {
if(is_file($file)){
$files[]=$file;
}
}
closedir($handle);
}
scandir lists files and directories inside the specified path.
Here is the most Efficient way based on this article's benchmarks:
function getAllFiles() {
$files = array();
$dir = opendir('/ABC/');
while (($currentFile = readdir($dir)) !== false) {
if (endsWith($currentFile, '.txt'))
$files[] = $currentFile;
}
closedir($dir);
return $files;
}
function endsWith($haystack, $needle) {
return substr($haystack, -strlen($needle)) == $needle;
}
just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.
Aside from scandir (#miku), you might also find glob interesting for wildcard matching.
If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:
<?php
$arr=scandir('ABC/');
?>
If you have other files, you should use glob as in Lawrence's answer.
$dir = "your folder url"; //give only url, it shows all folder data
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '.' and $file != '..'){
echo $file .'<br>';
}
}
closedir($dh);
}
}
output:
xyz
abc
2017
motopress

Display contents of multiple text files

I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}

Categories