Although I can find plenty of examples of listing all of the files in a directory
$dir = '../upload/'.$id.'/ask_temp';
But I need to get the name of a single file so I can store it in a variable to use elsewhere.
There is and only ever will be one file in there.
In regards to ComFreek's answer, make sure to filter out any directory. (. and ..)
I'm assuming you're using at least PHP 5.3
$files = array_filter(scandir($dir), function($val) use($dir)
{
return is_file($dir.'/'.$val);
});
$myFile = $files[0];
Another way is to this, this is probably easier. (first 2 are always '.' and '..')
$files = scandir($dir);
$myFile = $files[2];
Related
I am creating a WordPress plugin which allows a user to apply sorting rules to a particular template (page, archive, single etc). I am populating list of pages using PHP scandir like so:
$files = scandir(get_template_directory());
The problem is that I keep single.php templates in a '/single' subfolder so these templates are not being called by the above function.
How can I use multiple directories within the scandir function (perhaps an array?) or will I need a different solution?
So basically I am trying to:
$files = scandir( get_template_directory() AND get_template_directory().'/single' );
My current solution (not very elegant as it requires 2 for each loops):
function query_caller_is_template_file_get_template_files()
{
$template_files_list = array();
$files = scandir(get_template_directory());
$singlefiles = scandir(get_template_directory().'/single');
foreach($files as $file)
{
if(strpos($file, '.php') === FALSE)
continue;
$template_files_list[] = $file;
}
foreach($singlefiles as $singlefile)
{
if(strpos($file, '.php') === FALSE)
continue;
$template_files_list[] = $singlefile;
}
return $template_files_list;
}
First, there's not really anything wrong about what you're doing. You have two directories, so you do the same thing twice. Of course you could make it look a little cleaner and avoid the blatant copy paste:
$files = array_merge(
scandir(get_template_directory()),
scandir(get_template_directory().'/single')
);
Now just iterate over the single array.
In your case, getting the file list recursively doesn't make sense, as there may be subdirectories you don't want to check. If you did want to recurse into subdirectories, opendir() and readdir() along with is_dir() would allow you to build a recursive scan function.
You could event tighten up the '.php' filter part a bit with array_filter().
$files = array_filter($files, function($file){
return strpos($file, '.php');
});
Here I'm assuming that should a file start with .php you're not really interested in it making your list (as strpos() will return the falsy value of 0 in that case). I'm also assuming that you're sure there will be no files that have .php in the middle somewhere.
Like, template.php.bak, because you'll be using version control for something like that.
If however there is the chance of that, you may want to tighten up your check a bit to ensure the .php is at the end of the filename.
i have a problem/challenge on my Synology NAS. I have a IPcam connected which takes pictures with file names like:
00A8F700CB18()_1_20140107000224_3674.jpg
Now i would like to rename all those files to something like:
Tue 07-01-2014_11-17-26.jpg (containing date & time)
And here's the kicker: I've seen (PHP) scripts using "jhead" or "stat -c", unfortunately those are not an option on the Synology!
I cooked something up which works when i use a single file, now i would like to run this script on all the files in a directory!
Please help, i'm not an experienced PHP programmer and i take much joy in the explanation lines in the scrips, gives me and anybody who is whatching this post a learning curve ;)
The script u could use on a single file is something like this:
<?php
$stat = stat('/volume1/Ipcam/_Test/00A8F700CB18()_1_20140107000223_3673.jpg');
$motdate = ($stat['ctime']);
$newname = (gmdate("D d-m-Y_H-i-s", $motdate));
rename("/volume1/Ipcam/_Test/00A8F700CB18()_1_20140107000223_3673.jpg" . "/volume1/Ipcam/_Test/" . $newname . ".jpg");
?>
any help would be appreciated!
Read into scandir or readdir php functions.
They read a bunch of files in a specified directory and returns an array of file names.
You can then loop through these files and apply the above code to each file.
The examples on php.net are pretty easy to use and modify :)
You can use this modification of your code
<?php
$dir = '/volume1/Ipcam/_Test/';
$files = scandir($dir);
foreach($files as $file) {
$stat = stat($file);
$motdate = ($stat['ctime']);
$newname = (gmdate("D d-m-Y_H-i-s", $motdate));
rename($file, $dir . $newname . ".jpg");
}
?>
I have an HTML form and one of the inputs creates a folder. The folder name is chosen by the website visitor. Every visitor creates his own folder on my website so they are randomly generated. They are created using PHP Code.
Now I would like to write a PHP code to copy a file to all of the child directories regardless the quantity of directories being generated.
I do not wish to stay writing a PHP line for every directory that is created - i.e. inserting the filename name manually (e.g. folder01, xyzfolder, folderabc, etc...) but rather automatically.
I Googled but I was unsuccessful. Is this possible? If yes, how can I go about it?
Kindly ignore security, etc... I am testing it internally prior to rolling out on a larger scale.
Thank you
It is sad I cannot comment so go on...
//get the new folder name
$newfolder = $_POST['newfoldername'];
//create it if not exist
if(!is_dir("./$newfolder")) {
mkdir("./$newfolder", 0777, true);
}
//list all folder
$dirname = './';
$dir = opendir($dirname);
while($file = readdir($dir)) {
if(($file != '.' OR $file != '..') AND is_dir($dirname.$file))
{
//generate a randomname
$str = 'yourmotherisveryniceABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomname = str_shuffle($str);
$actualdir = $dirname.$file;
//copy of the file
copy($uploadedfile['tmp_name'], $actualdir.$randomname);
}
}
closedir($dir);
I just want to say, you seem to be lazy by looking for what you want to do. because when I read "I would like to write a PHP code to copy" the answer is in your sentence: copy PHP and list of folders regarless how many? Then just simply list it !
Maybe you need to learn how to use google... If you search "I would like to write a PHP code to copy a file to all of the child directories regardless the quantity of directories being generated" Sure you will never find.
I'm not a developer, but I'm the default developer at work now. : ) Over the last few weeks I've found a lot of my answers here and at other sites, but this latest problem has me confused beyond belief. I KNOW it's a simple answer, but I'm not asking Google the right questions.
First... I have to use text files, as I don't have access to a database (things are locked down TIGHT where I work).
Anyway, I need to look into a directory for text files stored there, open each file and display a small amount of text, while making sure the text I display is sorted by the file name.
I'm CLOSE, I know it... I finally managed to figure out sorting, and I know how to read into a directory and display the contents of the files, but I'm having a heck of a time merging those two concepts together.
Can anyone provide a bit of help? With the script as it is now, I echo the sorted file names with no problem. My line of code that I thought would read the contents of a file and then display it is only echoing the line breaks, but not the contents of the files. This is the code I've got so far - it's just test code so I can get the functionality working.
<?php
$dirFiles = array();
if ($handle = opendir('./event-titles')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$dirFiles[] = $file;
}
}
closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
$fileContents = file_get_contents($file);//////// This is what's not working
echo $file."<br>".$fileContents."<br/><br/>";
}
?>
Help? : )
Dave
$files = scandir('./event-titles') will return an array of filenames in filename-sorted order. You can then do
foreach($files as $file)
{
$fileContents = file_get_contents('./event-titles/'.$file);
echo $file."<br/>".$fileContents."<br/><br/>";
}
Note that I use the directory name in the file_get_contents call, as the filename by itself will cause file_get_contents to look in the current directory, not the directory you were specifying in scandir.
Simple question - How to list .htaccess files using glob()?
glob() does list "hidden" files (files starting with . including the directories . and ..), but only if you explicitly ask it for:
glob(".*");
Filtering the returned glob() array for .htaccess entries with preg_grep:
$files = glob(".*") AND $files = preg_grep('/\.htaccess$/', $files);
The alternative to glob of course would be just using scandir() and a filter (fnmatch or regex):
preg_grep('/^\.\w+/', scandir("."))
in case any body come to here,
since the SPL implemented in PHP, and offers some cool iterators, you may make use of the to list your hidden files such as .htaccess files or it's alternative hidden linux files.
using DirectoryIterator to list all of directory contents and excluding the . and .. as follows:
$path = 'path/to/dir';
$files = new DirectoryIterator($path);
foreach ($files as $file) {
// excluding the . and ..
if ($file->isDot() === false) {
// make some stuff
}
}