I have several files in a directory.I want to display all those filenames with the extension .txt and .jpeg
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo("/etrade/home/collections/utils");
if (($actual_file["extension"]== "txt") ||
($actual_file["extension"]== "jpg") ||
($actual_file["extension"]== "pdf")) {
//Require changes here.Dont know how to iterate and get the list of files
echo "<td>"."\n"." $actual_file['basename']."</a></td>";
}
}
closedir($handle);
}
Please help me on how to iterate and get the list of files .For instance I want all files with jpg extension in a seperate column and pdf files in a seperate column(since I am going to display in a table)
See if this does what you want (EDITED):
<?php
$ignoreFiles = array('.','..'); // Items to ignore in the directory
$allowedExtensions = array('txt','jpg','pdf'); // File extensions to display
$files = array();
$max = 0;
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if (in_array($file, $ignoreFiles)) {
continue; // Skip items to ignore
}
// A simple(ish) way of getting a files extension
$extension = strtolower(array_pop($exploded = explode('.',$file)));
if (in_array($extension, $allowedExtensions)) { // Check if file extension is in allow list
$files[$extension][] = $file; // Create an array of each file type
if (count($files[$extension]) > $max) $max = count($files[$extension]); // Store the maximum column length
}
}
closedir($handle);
}
// Start the table
echo "<table>\n";
// Column headers
echo " <tr>\n";
foreach ($files as $extension => $data) {
echo " <th>$extension</th>\n";
}
echo " </tr>\n";
// Table data
for ($i = 0; $i < $max; $i++) {
echo " <tr>\n";
foreach ($files as $data) {
if (isset($data[$i])) {
echo " <td>$data[$i]</td>\n";
} else {
echo " <td />\n";
}
}
echo " </tr>\n";
}
// End the table
echo "</table>";
If you just want to display two lists of files (it's not clear what part you're having trouble with from your question) can't you just store the filenames in an array?
You don't seem to be getting the file details - you're getting the pathinfo for /etrade/home/collections/utils, but you never add the file name to it.
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo($file);
switch ($actual_file['extension'])
{
case ('jpg'):
$jpegfiles[] = $actual_file;
break;
case ('pdf'):
$pdffiles[] = $actual_file;
break;
}
}
closedir($handle);
}
echo "JPG files:"
foreach($jpegfiles as $file)
{
echo $file['basename'];
}
echo "PDF Files:"
foreach($pdffiles as $file)
{
echo $file['basename'];
}
?>
Obviously you can be cleverer with the arrays, and have use multi-dimensional arrays and do away with the switch if you want.
Related
I'm trying to open a directory, read just files with a .txt format and then display the contents. I've coded it out, but it doesn't do anything, although it doesn't register any errors either. Any help?
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
$entry=array();
while(false!==($file = readdir($handle))) {
if ( !strcmp($file, ".") || !strcmp($file, "..")) {
}
else if(substr($file, -4) == '.txt') {
$entry[] = $file;
}
foreach ($entry as $txt_file) {
if(is_file($txt_file) && is_writable($txt_file)) {
$file_open = fopen($txt_file, 'r');
while (!feof($file_open)) {
echo"<p>$file_open</p>";
}
}
}
}
Help is quite simple.
Instead
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
write (I am sorry for re-formatting of new lines)
$dir = 'information';
if(is_dir($dir))
{
$handle = opendir($dir);
}
else
{
echo "<p>There is a system error</p>";
}
because if has to be written only smallcaps, thus not If.
And the second part rewrite to (again, you may use your own formatting of new lines)
$entry=array();
$file = readdir($handle);
while($file !== false)
{
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
foreach ($entry as $txt_file)
{
if(is_file($txt_file) && is_writable($txt_file))
{
$file_open = fopen($txt_file, 'r');
while(!feof($file_open))
{
echo"<p>$file_open</p>";
}
}
}
}
because PHP has elseif, not else if like JavaScript. Also I separated $file = readdir($handle) for possible source of error.
Code part
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
should be shortened only to
if(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
because when if part is empty, then it is not neccessary.
That is all I can do for you at this time.
Instead of iterating the directory with readdir, consider using glob() instead. It allows you to specify a pattern and it returns all files that match it.
Secondly, your while loop has an error: you conditionally add the file name to the list of files, but then you always print every file name using a foreach loop. On the first loop it will print the first file. On the second loop it will print the first and second files, etc. You should separate your while and foreach loops to fix that issue (i.e. unnest them).
Using glob, the modified code will look like:
$file_list = glob('/path/to/files/*.txt');
foreach ($file_list as $file_name) {
if (is_file($file_name) && is_writable($file_name)) {
// Do something with $file_name
}
}
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\"/>";
}
I'm trying to write a program that will open up a directory (in this case: files/), scan all of the filenames (not including any directories or ".." or ".") within this directory, and search for the filenames in the specified files from the "pages" array. If the filename is NOT found in the pages, the file will be moved to "unused-content".
My current code does not work. How can I achieve this goal?
<?php
if($handle = opendir('files/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[] = $entry;
}
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
Thank you!
You don't need all that long code .. all you need is FilesystemIterator
$pages = array("1.xml","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
$dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
foreach ( $dir as $file ) {
if ($file->isFile() && in_array(strlen($file->getFilename()), $pages)) {
// copy
// unlink
}
}
See another example using GlobIterator
Try to do something like this:
<?php
if($handle = opendir('files/')) {
$i=0;
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[$i] = $entry;
}
$i++;
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
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
}
}
?>
I wanna check if there any image on a folder from my server. I have this little function in PHP but is not working and I don't know why:
$path = 'folder/'.$id;
function check($path) {
if ($handle = opendir($path)) {
$array = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && count > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
}
closedir($handle);
}
Any help will be appreciated, thanks in advance.
It does not work because count is coming from nowhere. Try this instead:
$path = 'folder/'.$id;
function check($path) {
$files = glob($path.'/*');
echo empty($files) ? "$path is empty" : "$path is not empty";
}
Try this function: http://www.php.net/glob
Try This:
$path = 'folder/'.$id;
function check($path) {
if (is_dir($path)) {
$contents = scandir($path);
if(count($contents) > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
closedir($handle);
}
It counts the contents of the path. If there are more than two items, then its not empty. The two items we are ignoring are "." and "..".
Step 1: $query = select * from your_table where id=$id;
Step 2: $path=$query['path_column'];
Step 3: if($path!=null&&file_exit($path)&&$dir=opendir($path)){
while (($file = readdir($dir )) !== false)
{
if ($file == '.' || $file == '..')
{
continue;
}
if($file) // file get
{
$allowedExts = array("jpg");
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($extension, $allowedExts))
$file[]=$file;
}
$data[file_name'] = $file;
}
closedir($dir);
}