Iterating through folders - php

I have been using a snipit I found online to display the files and folders in a directory with my PHP script. This part works fine, but I would like to be able to click the folders and get a similar html page up that displays it's contents, and beeing able to open the text files in the browser(this works fine if the text file is in the start directory).
At the moment, when I click a folder, an old school sort of page opens up with no html file in it. Is the only way to do this to create a new PHP script in each folder and link to it? I tried using the DirectoryIterator class, but it gave me an error. I dont have the snipit for DirectoryIterator anymore, but it was something like "Can't find class DirectoryIterator".
Here's the code I'm using now(working):
$arrayImports = array ();
if ($handle = opendir ($importLogPath)
{
while (false !== ($entry = readdir ()))
{
chop ($entry);
if ($entry != "." $entry != "..")
{
$arrayImports [] = "<p><a href=$importLogPath$entry target=_blank>$entry</a></p>";
}
}
closedir($handle);
}
arsort ($arrayImports);
foreach ($arrayImports as $value)
{
print "<li>$value</li>";
}
Thanks!

Are you looking for something like this?
Encode Explorer
I used it for an old project... it's very cool. You can also add ajax to browse folders without refreshing the pages.
Bye

Related

Displaying a recently uploaded file with an image and a link to the file

I currently have 5 images on my site and each of these is linked to a file, I have recently added an option to upload a file to the directory "uploads", but I would like for these to be echoed on the site with an image (I have a folder of images named numerically).
Is it possible to create a loop to check if file has been added to a specific directory, e.g. "folder/file.doc"?
I don't have any code for this and I don't expect anyone to code it for me, but if you could please point me in the right direction as to how to make this.
Maybe this could help? You just need to read the folder and iterate over all the content while echoing all files with name, link and tag:
if ($handle = opendir('/path/to/your/files')) {
while (false !== ($entry = readdir($handle))) {
echo "<img src='$entry'/><br/>";
}
closedir($handle);
}
And this is the corresponding link:
http://php.net/manual/de/function.readdir.php#example-2478

PHP file_get_contents to get jquery min code

I am writing a script that will go through all my .js files and minify them into one .php file to be included on the site. I just run this script after I have edited some js and want to upload it to the live site.
The issue: I can not load the content of jquery-2.1.4.min.js using file_get_contents. I have tried changing the name of the file to jquery.js and that did not help. I do not have any complex javascript in the other files (just random strings) but they open fine.
With the code:
if (!file_get_contents($filename)) {
die ("dammit");
}
I get the response of "dammit". All other files are fine though, so I know the file name and path are correct. One of the weird things is that there are no errors coming up (I have used error_reporting (-1); to make sure they will).
Is anyone else able to get the file contents of jquery? Any ideas what would cause this and if it will be a problem with other javascript or css?
As requested, here is the full code:
$buffer = $jsStartBuffer;
//get a list of files in the folder (only .js files)
$fileArray = array();
if (is_dir($jsMakeFile["SourcePath"])){
if ($dh = opendir($jsMakeFile["SourcePath"])){
while (($file = readdir($dh)) !== false){
$file_parts = pathinfo($jsMakeFile["SourcePath"].$file);
if ($file_parts['extension'] == "js") {
$fileArray[] = $file;
}
}
}
}
print_r($fileArray);
foreach ($fileArray as $nextRawFile) {
$buffer .= file_get_contents($jsMakeFile["SourcePath"].$nextRawFile);
if (!file_get_contents($jsMakeFile["SourcePath"].$nextRawFile)) {
die ("dammit");
}
echo $jsMakeFile["SourcePath"].$nextRawFile;
}
$buffer .= $jsEndBuffer;
echo $buffer;
$buffer = \JShrink\Minifier::minify($buffer);
file_put_contents($jsMakeFile["finalFile"]["path"].$jsMakeFile["finalFile"]["name"], $buffer);
When I put other .js files in there it is fine (I even tried lightbox.min.js and it worked fine!) I have tried a few different versions of jquery.min and they all seem to fail.
OK, solution found. It is to do with the actual file created by jquery.
The way I solved it was:
- Go to the query site, and instead of downloading the required file, open it in a new tab/window
- Copy all the content in this window
- Create a new file where required and name as required
- Paste the content into this file and save it
This new file will now be able to be read by file_get_contents. I would imagine this solution would help if you are trying to work with jquery (and other) files in php in any way and having issues.

PHP: get content from first file in folder and then delete it

Using PHP, I want to get the content from the first file in a folder and when the content is loaded, delete the file. Here is what I have:
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
if($entry != '.' && $entry != '..') {
echo $entry = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
break; // only need the first file
}
}
The code above loads the first file in the folder and I can delete it successfully using something like
unlink("temp.txt");
So there are no permission denied errors. BUT what I need to do is delete the file by its variable name (because every filename is different). Surprisingly for me, unlink("$entry"); or something similar does not let me delete it, instead showing a warning along with the first few lines of the content of that file. If I echo $entry It shows temp.txt correctly. Can someone enlighten me? What am I missing here?
(Optional (un)related question: If I have numeric files like 1.txt, 2.txt, 3.txt, 10.txt... . Is there a way I could modify the code above in a way, that it does not load files like 1,10,2,3 ..., instead load it like 1,2,3,10...?)
UPDATE:
The updated code that works (for future reference):
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
if($entry != '.' && $entry != '..') {
echo $b = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
break; // only need the first file
}
}
unlink("./$entry");
The first problem is that you're overwriting $entry with the file contents, as such the filename is no longer valid when trying to delete it (explaining the error with the file contents).
Secondly, because you're using FILE_USE_INCLUDE_PATH you don't know exactly where the file is located, and unlink resolves related to the current working directory, which is most probably not $a.
Use unlink($a.'/'.$entry) and you'll be fine.
As for the unrelated question - use scandir to get all the files in the folder, then apply natsort to the resulting array to sort by a 'natural sorting algorithm'. Keep in mind that a directory listing always also lists the folders . and .. which you'll have to detect and skip or remove manually.

php echo file url using title tag

I have a php script that will echo a list of files from a folder and display them randomly on my page.
At the moment it displays the url of the file for example: what-can-cause-tooth-decay.php
i would like it to display the page title <title>What can cause tooth decay</title>.
Current code:
<?php
if ($handle = opendir('health')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach($fileTab as $file) {
$thelist .= '<p>'.$file.'</p>';
}
}
?>
<?=$thelist?>
Many thanks
I see a couple of possible approaches:
You could parse the files. Should be possible by running a regex over the results of file_get_contents.
Place some text file somewhere, which maps file names to titles. Load it into memory and use it to populate an array which you can use to map the file names. Let it have file_name.html Title on each line, or something like that.
Use a naming convention, so the titles can be inferred from the filenames. Something like "capizalize first letter, turn '_' into space"
Downsides of the 2nd and 3rd approach: You'd have to keep it consistent with the actual title-elements in the files. Problem with the first approach: You have to read every file into memory - could be a performance problem with many/big files. To solve this, I could imagine writing a script which looks through all the files and generates the lookup text file. Whenever you change a title in a file, or add/remove files, you'd just need to rerun that script.

Trying to echo contents of multiple text files while sorting the output by the file name - PHP

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.

Categories