how to hide a file from readdir() php - php

My code loops through a directory and displays all the files and folders where I have a index.php file that I don't want to be displayed.
<?php
$directory = 'jocuri';
$row = 0;
if ($handle = opendir($directory.'/'))
{
echo '<table border="1">';
while ($cat = readdir($handle))
{
if ($cat != '.' && $cat != '..')
{
if($row==0) echo '<tr>';
echo '<td align="center">';
echo ' <a href="'.$directory.'/'.$cat.'" style="text-decoration:none">';
echo ' <img src="'.$directory.'/'.$cat.'/image.php" style="display:block" />'.str_replace('_', ' ', $cat);
echo ' </a>';
echo '</td>';
if($row == 2)
{
echo '</tr>';
$row = -1;
}
$row++;
}
}
echo '</table>';
}
?>
How can i achieve that?

Staying quick and dirty:
if ($cat != '.'&&$cat != '..' && $cat != 'index.php'){ ... }
But I'll definitely move to some more consistent method like FilesystemIterator or glob().

while($cat = readdir($handle)) {
if (in_array($cat, array('.', '..', 'index.php')))
continue;
// display the file here
}

Related

How to create dynamic table from both directory and CSV files

I need to create a table whose first column is populated from subdirectory names inside a directory and rest are from a CSV file. This have to be a dynamic table and table headers have to be added from the code. What's wrong with my code?
I am an absolute beginner. So, please ignore my stupidity.
$dir = 'D:\workspace';
$dirlist = preg_grep('/^([^.])/', scandir($dir));
$row = 1;
if (($handle = fopen("D:\workspace\demo\database.csv", "r")) !== FALSE) {
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
foreach ($dirlist as $rowdirectory)
{
echo '<td>' . $rowdirectory . '</td>';
echo '<td>'.$value.'</td>';
}
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
<?php
#------------------------------------------Function for Reading Directory-------------------------------------------
function readdirectory($dir)
{
$dirlist = preg_grep('/^([^.])/', scandir($dir)); // for all(./../anything that
starts with .)
//$dirlist = preg_grep('/[^.]/', scandir($dir)); //only . & ..
//$dirlist =preg_grep('/^[(^.)]/', scandir($dir));//only files that starts with .
return $dirlist;
}
#------------------------------------------Function for Reading CSV file-------------------------------------------
function readcsvfile($source)
{
$handle = fopen($source, "r");
$filecontent = null;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$filecontent[] = $data;
}
fclose($handle);
return $filecontent;
}
$filecontent= readcsvfile("D:\workspace\demo\database2.csv");
#-------------------Directory Function calling, header array cration and other declaration------------------------------------
$conf_prefix= "../";
$conf_suffix="index.php";
$headerarray= $filecontent[0];
#var_dump($headerarray);
$headersize= count($headerarray);
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
$dir = 'D:\workspace';
$dirlist= readdirectory($dir);
#------------------------------------------Creating 1st row/Header row of Table-------------------------------------------
echo '<tr>';
for($a=0; $a<$headersize;$a++)
{
echo '<td>'.$headerarray[$a].'</td>';
}
echo '</tr>';
#-----------------------------Creating Table elements by comparing both directory arrays and CSV file array-------------------------------------------
foreach ($dirlist as $rowdirectory)
{
foreach ($filecontent as $value) {
$num = count($value);
if ($rowdirectory== $value[0])
{
$link= $conf_prefix. $rowdirectory."/".$conf_suffix;
echo '<tr>';
echo '<td> ' . $rowdirectory . ' </td>';
for( $c=1; $c < $num; $c++) {// loop for csv file
{
echo '<td>'.$value[$c].'</td>';//else print "value"
}
}
echo '</tr>';
}
}
}
?>

php sort values of a array

id love a little help with the sort function here, im trying to figure it out but cant.
<?php
if ($handle = opendir('uploads')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."){
sort ($file);
$thelist .= '<li>'.$file.'<img src="uploads/'.$file.$media.'" width="25" height="25"</li>';
}
}
closedir($handle);
}
?>
<ul><?php echo $thelist; ?></ul>
so this doesnt sort...
and the following will, but wont display some files.
im only interested in the sort function for the top code, i paid a guy to write the following half to try to understand the function sort
from what i can figure were suggesting the $file displays for a list then for a photo using the various $.. im stuck with whats stopping the $file from getting alphabeticaly arranged before being told what to display, (the best i got to was a list of the number ones displaying alphabetical (numerical yes) but its not sorting)
function showDir($dir, $i, $lar, $lon, $lin)
{
print("<style>.box { border-style: outset ; border-width: 1px ; border-color: #A3C5CC ; border-radius: 8px ; -moz-border-radius: 8px }</style>") ;
print("<script language='JavaScript'>
<!--
function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
//-->
</script>") ;
$i++;
if($checkDir = opendir($dir))
{
$cFile = 0;
while($file = readdir($checkDir))
{
if($file != "." && $file != "..")
{
if(!is_dir($dir . "/" . $file))
{
$listFile[$cFile] = $file;
$cFile++;
}
}
}
if(count(#$listFile) > 0)
{
print("<table cellspacing='1' cellpadding='0' border='0'><tr>") ;
sort($listFile);
$x = 0 ;
for($k = 0; $k < count($listFile); $k++)
{
$spacer = "";
for($l = 0; $l < $i; $l++)
$spacer .= " ";
if($x % $lin == 0)
print("</tr><tr>") ;
$img = $listFile[$k] ;
$tmp = explode(".", $img) ;
$x++ ;
if($tmp[1] == 'jpg' OR $tmp[1] == 'bmp' OR $tmp[1] == 'gif' OR $tmp[1] == 'png'
OR $tmp[1] == 'tga' OR $tmp[1] == 'tif' OR $tmp[1] == 'eps')
{
print("<td>") ;
print("<table class='box' bgcolor='#9ABBC1' cellspacing='0' cellpadding='0' border='0' width='" . ($lon+10) . "' height='" . ($lar+27) . "'><tr>") ;
print("<td align='center'><small><b>" . ($k+1) . "</b></small></td></tr><tr>") ;
print("<td align='center'>") ;
$srcimg = $dir . "/" . $spacer . $img ;
list($width, $height, $type, $attr) = getimagesize($srcimg);
print("<a href='#' onClick=\"MM_openBrWindow('display.php?img=$srcimg&lon=$width&lar=$height','','width=" . $width . ",height=" . $height . ",left=100,top=100,scrollbars=no,toolbars=no')\">") ;
print("<img src='" . $srcimg . "' width='" . $lar . "' height='" . $lon . "' alt='" . $img . "' title='" . $img . "' border='0'></a></td>");
print("</tr></table>\n") ;
print("</td>") ;
}
else
$x-- ;
}
print("</tr></table>\n") ;
print("<br><small>" . $k . " Images displayed<b></b></small>") ;
}
closedir($checkDir);
}
}
}
?>
You should use scandir function instead of readdir.
sorting_order By default, the sorted order is alphabetical in
ascending order. If the optional sorting_order is set to
SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in
descending order. If it is set to SCANDIR_SORT_NONE then the result is
unsorted.
<?php
if ($handle = opendir('uploads')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."){
$files[] = $file;
}
}
sort ($files);
$thelist = '';
foreach ($files as $file) {
$thelist .= '<li>'.$file.'<img src="uploads/'.$file.'" width="25" height="25"</li>';
}
closedir($handle);
}
?>
<ul><?php echo $thelist; ?></ul>

Displaying SQL-data in a table

A few months ago, I made a system where people could upload a picture and then those pictures would be displayed in a table with 4 columns.
Now I am working on a project (to practice my php, I am still learning it) and I would like to use a similar system as below but it should display data from a database.
The result I was trying to achieve is the data being displayed in 2 columns.
if ($handle = opendir('images/')) {
$bool = true;
while ($bool) {
$td = 1;
echo '<tr>';
while ($td < 4) {
$file = readdir($handle);
if ($file != '.' && $file != '..' && $file != '.DS_Store') {
echo '<td>';
if ($file) {
echo '<img src="images/'.$file.
'">';
} else {
$bool = false;
}
echo '</td>';
$td++;
}
}
echo '</tr>';
}
}
closedir($handle);
For anyone looking for the answer:
$query = "SELECT * FROM webshop";
if($query_run = mysql_query($query)) {
$bool = true;
echo '<table>';
while($bool) {
$td = 0;
echo '<tr>';
while($td < 2) {
if($fetch = mysql_fetch_assoc($query_run)) {
echo '<td>';
$title = $fetch['title'];
$info = $fetch['info'];
/* Commented out for now, will be implemented later
$image = $fetch['image'];
$price = $fetch['price'];
*/
echo $title;
} else {
$bool = false;
}
echo '</td>';
$td++;
}
echo '</tr>';
}
echo '</table>';
}

Populate selectbox with directories

I have the following code. I'm looking to do what's in the comment which is to populate a selectbox with a name of directories. How would I do that?
$path = 'repository/' . $name[0];
$results = scandir($path);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
//extract directory names and populate selectbox
}
}
At maybe its simplest:
echo "<select name=\"something\">";
foreach(glob("repository/{$name[0]}/*", GLOB_ONLYDIR) as $dir) {
echo "<option>$dir</option>";
}
echo "</select>";
A quick and dirty solution, assuming result is the directory you want to show:
echo '<select id="directories" name="directories">';
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
echo '<option value="' . $result . '">' . $result . '</option>';
}
}
echo '</select>';
Perhaps I've not understood the question but surely it's just:
<?php
$selectString = '<select>';
$path = 'repository/' . $name[0];
$results = scandir($path);
foreach ($results as $result) {
if ($result === '.' or $result === '..') {
continue;
}
if (is_dir($path . '/' . $result)) {
$selectString .= "<option>{$result}</option>";
}
}
$selectString .= "</select>"
You can then put $selectString wherever you need it.

Highlight every other row of a table in a foreach loop and highlight columns depending on value of row

I had a really long description written for my problem, but I've progressed and have managed to get it partially working... I basically want every other row in a table to be a different color - and to highlight certain rows if they meet a condition that I set.
foreach ($data as $row) {
$style = null;
while (($values = fgetcsv($handle, 0, '|')) !== false) {
$comment_lines = $values[6];
$priority = $values[7];
$time_worked = $values[11];
$var_X = strpos($priority, '1');
$var_C1 = strpos($comment_lines, 'CCB');
$var_C2 = strpos($comment_lines, 'CEB');
$var_U = empty($time_worked);
}
if (empty($values[0]) && count($values) === 1) {
continue;
}
if (strlen($var_X)) {
echo '<tr class="gradeX">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
} else if ($var_C1 !== false) {
echo '<tr class="gradeC">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
} else if ($var_C2 !== false) {
echo '<tr class="gradeC">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
} else if ($var_U !== false) {
echo '<tr class="gradeU">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
} else if ($odd) {
$odd = !$odd;
echo '<tr class="even gradeA">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
} else {
$odd = !$odd;
echo '<tr class="odd gradeA">';
foreach ($values AS $index => $value) {
echo '<td>' . $value . '</td>' ;
}
}
echo '</tr>';
}
Right now, only the 'every other' is working. I can't get the gradeX, gradeC and gradeU to show anything...
EDIT:
This is the working code, cheers.
while (($values = fgetcsv($handle, 0, '|')) !== false) {
$style = null;
$comment_lines = $values[6];
$priority = $values[7];
$time_worked = $values[11];
$var_X = strpos($priority, '1');
$var_C1 = strpos($comment_lines, 'CCB');
$var_C2 = strpos($comment_lines, 'CEB');
$var_U = empty($time_worked);
if (empty($values[0]) && count($values) === 1) {
continue;
}
if ($var_X !==false) {
echo '<tr class="gradeX">';
} elseif ($var_C1 !== false) {
echo '<tr class="gradeC">';
} elseif ($var_C2 !== false) {
echo '<tr class="gradeC">';
} elseif ($var_U !== false) {
echo '<tr class="gradeU">';
} else {
//nothing
}
foreach ($values as $index => $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
In your loop you need to add a counter to identify whether you're currently on an 'even' or an 'odd' iteration, and then add either class 'odd' or 'even' into the as you output it.
There's a related question already on here that covers that here: php: how to add odd/even loop in array
The other parts should be fairly easy by using if statements to check if the relevant data exists or not.
For example, strlen will tell you whether a variable has length or not (to put out 'gradeX'), and strpos will allow you to check if a varibale contains a string (for 'gradeC').
If you can target IE later than IE8 and forget about IE8, you can use CSS3:
tr:nth-child(odd) {
background-color: #EEEEEE;
}
tr:nth-child(even) {
background-color: #FFFFFF;
}

Categories