content reading of multiple files in php - php

I m new to PHP so please bear me
There is a dir name filename which contains diff sub-dir
in these sub-dir there are some .md files
I want to get the content of all of these files and show it like
Filename:""
Content: ""
I tried to use this but no luck
<?php
$directory = "./dirname";
$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);
?>

Related

php list files to array and save array stringified to disk [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 9 months ago.
In my web app I want to list in php the contents of a directory "archives/*-pairings.txt"
So I have a php file (below) that is supposed to read those contents into an array and write the file "archives/contents.json" containing json.
contents.json should look like this:
["2012-01-02-pairings.txt","2012-05-17-pairings.txt","2021-03-17-pairings.txt"]
I tried the code below (from the web) but "contents.json" was just blank.
How can I do this?
<?php
$arrFiles = array();
$iterator = new FilesystemIterator("archives");
foreach($iterator as $entry) {
$arrFiles[] = $entry->getFilename();
}
$myfile = fopen("archives/contents.json", "w");
fwrite ($myfile, $arrFiles);
fclose ($myfile);
?>
The same result was with the code below:
<?php
$arrFiles = array();
$objDir = dir("archives");
while (false !== ($entry = $objDir->read())) {
$arrFiles[] = $entry;
}
$objDir->close();
$myfile = fopen("archives/contents.json", "w");
fwrite ($myfile, $arrFiles);
fclose ($myfile);
?>
function list_contents($dir) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'contents.json') {
$contents[] = $file;
}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/contents.json', $contents_json);
}
This works for me a simple function that reads the files at the directory and puts it into contents.json.
Easily changed to this if you want it to have a specific suffix:
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'contents.json') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/contents.json', $contents_json);
}

how to work with directory in php

the code is
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(($file = readdir($dir)) !== false) {
if($file !== '.' && $file !== '..') {
$files[] = $file;
}
}
closedir($dir);
//sort($files);
$i=0;
foreach($files as $key) {
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$files[$i]'></iframe>";
break;
}
?>
i want to show templates onclick next/prev button.horizontally.
like slider.
please help
Correct logic to iterate a directory in while loop is false != ($file = readdir($dir)), where you assign file name first and check it's not false.
Also you can print title with $key itself. $files[$i] and $i variable is not required.
In order to iterate through all files of directory remove break, this will cause to end the loop after first iteration.
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(false != ($file = readdir($dir)))
{
if($file !== '.' && $file !== '..')
{
$files[] = $file;
}
}
closedir($dir);
//sort($files);
foreach($files as $key)
{
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$key'></iframe>";
}
?>

Search for a folder and and get the content of the files inside

I'm trying to search for a folder and retrieve the files inside of the folder (get content) I'm able to search for the folder using the follow code but I can't pass from there I can't see the content an retrieve the files inside. The files inside will be txt files and I would like to be able to open and see then.
How can achieve what i want? Thank you.
<?php
$dirname = "C:\windows";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];
$dir = opendir($dirname);
while(false != ($file = readdir($dir))){//Loop for every item in the directory.
if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file !=
"search.php"))//Exclude these files from the search
{
$pos = stripos($file, $findme);
if ($pos !== false){
$thereisafile = true;//Tell the script something was found.
echo'' . $file . '<br>';
}else{
}
}
}
if (!isset($thereisafile)){
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>
New code
<?php
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];
$files = scandir($dirname);
foreach ($files AS $file)
{
if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;
if (stripos($file, $findme) !== false)
{
$found = true;
echo 'FOUND FILE ' . $file . '<hr>';
echo 'OPENING IT:<br>';
echo file_get_contents($dirname . $file);
echo '<hr>';
}
else
{
echo 'not found: ' . $file . '<br>';
}
}
if (!isset($found))
{
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
The following code uses a recursive function for searching the directory. I hope it’ll solve your problem.
function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
foreach($files as $file){
$arr[] = $dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
$arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
}
}
return($arr);
}
$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
foreach($files as $file){
$_file = $dirname.DIRECTORY_SEPARATOR.$file;
echo "$file<br/>";
}
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}

Pull Images from directory - PHP

I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.
<img src="plates/photo1.jpg">
That's it. It seems so simple but all of the code I have found basically doesn't work.
What I have that I am trying to make work is this:
<?php
$a=array();
if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.png$/", $file))
$a[]=$file;
else if(preg_match("/\.jpg$/", $file))
$a[]=$file;
else if(preg_match("/\.jpeg$/", $file))
$a[]=$file;
}
closedir($handle);
}
foreach($a as $i){
echo "<img src='".$i."' />";
}
?>
This can be done very easily using glob().
$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
print "<img src=\"plates/$file\" />";
You want your source to show up as plates/photo1.jpg, but when you do echo "<img src='".$i."' />"; you are only writing the file name. Try changing it to this:
<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
You should use Glob instead of opendir/closedir. It's much simpler.
I'm not exactly sure what you're trying to do, but you this might get you on the right track
<?php
foreach (glob("/plates/*") as $filename) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == "png") {
// do something
} elseif($path_parts['extension'] == "jpg") {
// do something else
}
}
?>

Scan current folder using PHP

I have a folder structure like this:
/articles
.index.php
.second.php
.third.php
.fourth.php
If I'm writing my code in second.php, how can I scan the current folder(articles)?
Thanks
$files = glob(dirname(__FILE__) . "/*.php");
http://php.net/manual/en/function.glob.php
foreach (scandir('.') as $file)
echo $file . "\n";
From the PHP manual:
$dir = new DirectoryIterator(dirname($path));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
<?php
$path = new DirectoryIterator('/articles');
foreach ($path as $file) {
echo $file->getFilename() . "\t";
echo $file->getSize() . "\t";
echo $file->getOwner() . "\t";
echo $file->getMTime() . "\n";
}
?>
From The Standard PHP Library (SPL)
It depends on what you mean by 'scan' I'm assuming you want to do something like this:
$dir_handle = opendir(".");
while($file = readdir($dir_handle)){
//do stuff with $file
}
try this
$dir = glob(dirname(__FILE__));
$directory = array_diff(scandir($dir[0]), array('..', '.'));
print_r($directory);
Scan current folder
$zip = new ZipArchive();
$x = $zip->open($filepath);
if ($x === true) {
$zip->extractTo($uploadPath); // place in the directory
$zip->close();
$fileArray = scandir($uploadPath);
unlink($filepath);
}
foreach ($fileArray as $file) {
if ('.' === $file || '..' === $file)
continue;
if (!is_dir("$file")){
//do stuff with $file
}
}
List all images inside a folder
$dir = glob(dirname(__FILE__));
$path = $dir[0].'\\images';
$imagePaths = array_diff( scandir( $path ), array('.', '..', 'Thumbs.db'));
?>
<ul style="overflow-y: auto; max-height: 80vh;">
<?php
foreach($imagePaths as $imagePath)
{
?>
<li><?php echo '<img class="pagina" src="images/'.$imagePath.'" />'; ?></li>
<?php
}
?>
</ul>

Categories