I'm making a simple file listing function in PHP, just to recursively list all the files in a directory.
The function I have right now looks something like this:
<?php
function listFiles($dir){
echo "<ul class=\"filebrowser\">";
$dirCont = scandir($dir); // scan the whole directory
sortFoldersFirst($dirCont,$dir); // sort alphabetically, folders first
foreach ($dirCont as $value) {
if (!in_array($value,array(".","..",".deleted"))){ // don't list the parent folder, current folder, or the (hidden) .deleted folder
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){ // if it's a folder
echo "<h3 class=\"filebrowser\">" . $value . "</h3>"; // show the folder name
listFiles($dir . DIRECTORY_SEPARATOR . $value); // do the same again for the child folder
} else {
echo "<li>".$value."</li>"; // a link to the file
}
}
}
echo "</ul>";
}
?>
This gives me something like this:
This technique works just fine, however, I'd like to store a little more information about the files, like the author, comments, maybe a link to a thumbnail etc.
I'd like to get rid of the 'real' directory structure, and store everything in a database. (Just all files in 1 big folder, and links to the files in the database, not the actual files)
How can I store this information in the database, and how can I get it back out, without changing the result in the browser.
In other words: how can I get the tree structure in and out of the database, and how do I recursively loop through it.
I found this answer.
It shows how to make a database tree structure by saving the parent folder's id for every file/folder. This makes it easy to get the full path of a file, but it seems a bit less convenient to list all contents of a folder.
Is there a better solution to this problem?
Thanks in advance,
Pieter
Related
I am completely new in PHP and I am trying to achieve simple goal and I need your help please.
I would like to write a script that would take an array of values and delete all the files from the parent folder.
So basically loop in array of file names, and for each name from the array try to find file with same name and if found -> delete it.
So far I achieved to get list of files from the parent folder by using $files = scandir('../');
I cannot find a syntax that would take a list of names and then loop through the $files and deletes everything that match the name from the provided list.
Example:
array ('1.jpg', '2.jpg') -> List of file names that I need to delete
$files = scandir('../') -> List of actual files in the parent folder
action -> 'deleted file '1.jpg' and '2.jpg' from the parent folder
I hope that it is understandable what I am trying to achieve :D
Thanks a lot!
I was able to delete one file in the parent folder using "hardcoded" name
<?php
$path = '../config.php';
if (!unlink($path)) {
echo 'File not deleted';
} else {
echo 'File' . $path . ' deleted successfuly!';
}
I also tried to get a list of all files in the parent folder using
<?php
$files = scandir('../');
var_dump($files);
I came up with this questioin. My background is from the Node.js. I am not usually quite used to be in PHP. That's why I'm aksing this question to solve the current issues.
The issues is that's to says I have certain Files and Folders that contains with a specific letters and number at the beginning. As you can see given by down below with a scrrenshot.
I just learn and writing some php code that I grabbed it from the internet resources. Take a look at what's my code:
I want this to detele this all folders which contains letters "exp_" and all the files names start with this numbers "xx-xx-xx" etc.
I created delete.php. When I'd called this file via the browser, I want to achieve to delete all the files and folder which for the No. 1 case.
All these folders and files are generated in everdays. That's why I do want to clean all those data.
<?php
$path = "test";
if(!unlink($path)){
echo "File has not deleted yet.";
} else {
echo "Successfully deleted!";
}
?>
Is there any how any solution to solve this issues? I will appreciate all in advanced who are giving me idea and suggestions from you guys.
You can do something like this:
$files = new DirectoryIterator(__DIR__);
foreach ($files as $file) {
if ( ($file->isDir() and strpos($file->getFilename(),'exp_')!==false) || ($file->isFile() and $file->getFilename() == date('d-m-Y') ) ) {
unlink($file->getPathname());
}
}
Thus, all folders with names like exp_ and files with today's date will be deleted.
Delete files which are not in a mySQL TABLE
The link above is to a Stack Overflow question with an answer that is (I believe) pretty close to what I'm looking for. I'm actually just seeking further clarification on the answer given.
The Question
I'm trying to delete files (picture files) in a folder only if they're
not present in a specific database table.
Just like a check of filenames and if they're present in the table
it's ok but if not delete them.
Any ideas how to do that?
The accepted answer
$result = mysql_query("SELECT filename FROM no_delete");
while($row = mysql_fetch_assoc($result)) {
$do_not_delete[] = $row['filename']; }
foreach(glob("*") as $filename) {
if (!in_array($filename, $do_not_delete)) {
//delete them
}
}
I'm not too savvy with PHP, but I don't believe they are specifying a folder path on the server here, are they? I'd like to be able to look inside a specific folder and check whether any images in that folder are within any database tables. If not, delete that image.
Before calling glob("*") just add a line chdir(""). Then you can search whichever directory you want to look at. I just went one level higher in the call below. You may specify whichever directory you want. Before doing a delete, just add an echo statement to $filename to verify if the correct files are being deleted.
chdir("../");
foreach(glob("*") as $filename) {
if (!in_array($filename, $do_not_delete)) {
//delete them
}
As described in this answer the first parameter, i.e. pattern, can contain the path to a directory relative to the current working directory of the script (which can be changed with chdir()) or an absolute path.
Consider this example from this tutorial page:
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}
I'm creating a method that will inspect files in an upload folder and some of these files are archive (tar, tar.gz, zip, rar, etc). I would like to read these archive files and list all files in a nested tree format.
For example, I have an archive file called sandwich.tar.gz, I would like it to be listed as below:-
sandwich.tar.gz
lettuce
mayonaise
cheese
bread (directory)
wholemeal
My code thus far:-
<?php $archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach($archive as $file) {
echo $file . "<br />";
}
But it failed to list files inside the bread directory. How do I fix this?
You can do this using a RecursiveIteratorIterator, because PharData extends the Phar class and the Phar class extends the RecursiveDirectoryIterator class:
$archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach (new RecursiveIteratorIterator($archive) as $file) {
echo $file . "<br />";
}
Although this question is rather dated, considering the stupidity and the uselessness of the previous answer, I cannot but reply.
It seems whatever PHP does is always non-standard and awkward at best...
You got it right to inspect the first level. However, the objects returned from the iteration are not of the same type, thus calling foreach on them will lead to failure.
Iterating on a PharData object gives you PharFileInfo ones. From there you can check for the file type (checking if it is a directory with the inherited isDir() method).
From there, you will need to create another PharData object on the path to the resource obtained from the (also inherited) getPathname() (sic, not getPathName() say the docs!) method. You will then be able to iterate over it...
Full example:
<?php
$archive = new PharData('/upload/directory/sandwich.tar.gz');
foreach($archive as $file) {
echo $file;
if($file->isDir()) {
echo ':';
$dir = new PharData($file->getPathname());
foreach($dir as $child) {
echo "<br />$child";
}
}
echo "<br />";
}
?>
Of course, that kills easy recursion if you have multiple levels in your archive. You will have to cook your own recursive crawler...
Some advice that I was given once, and think about often, comes to mind: code will do EXACTLY what you ask it to do: nothing more, nothing less.
Ask the machine: 'if this is a directory, please display the contents?'
Your function thinks that it is looking for a $file, and thus outputs the name of that file.
Consider http://php.net/manual/en/function.readdir.php and http://www.php.net/manual/en/function.is-dir.php
I'm building a super simple CMS in PHP, and have what's probably a simple question...
I'm storing my news in .txt files (I know it should be a database, I'm just not focusing on that stuff for now...) and need to display these files on a page (news.php). It should basically print the contents of each file in reverse alphabetical order, for example:
Files:
12-11-11.txt
12-12-11.txt
12-13-11.txt
12-14-11.txt
Display:
Contents of 12-14-11.txt
Contents of 12-13-11.txt
Contents of 12-12-11.txt
Contents of 12-11-11.txt
I'd like to wrap each post in something like <div class="article"></div>.
I'm very new to PHP so a good code example would be lovely. I'm storing my files like this:
news page: /news.php
news files: /edit/news/
foreach (glob("/edit/news/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}