if folder is empty echo message, if not show all jpg files - php

im trying to echo all jpg image files in a folder.
it works, but i dont have the line to show an error that the folder is empty written properly. it shows a php script error instead,
another problem is that i have one .txt file in the directory, this
one will read the text for the certain page. the rest of the script
will echo the jpg files. it might not echo zero files because of that
text file
folder = cat the gategory name/title .txt file = the text for the page
.jpg files = are the categories pictures
error is:
Warning: Invalid argument supplied for foreach() in /home/ranshow/domains/show.webking.co.il/public_html/modules/attractions.php on line 67
Gallery is empty, no pics to show
0
<div style="text-align: center;margin-top:25px;margin-bottom: 50px;">
<?
$count = "0";
foreach (glob("attractions/$cat/*.jpg") as $filename) {
$count++;
$files[] = $filename;
$filename = urlencode($filename);
}
if($count == "0") { echo "Gallery is empty, no pics to show"; }
else {
?>
<?
foreach ($files as $filename) {
?>
<a id="thumb1" href="img.php?img=<?=$filename;?>" class="highslide" onclick="return hs.expand(this)">
<img src="img.php?img=<?=$filename;?>" width="167" height="150" style="margin: 2px;d0b28c;padding:1px;border: 1px solid #c1c1c1;">
</a>
<?
}
?>
<?
}
?>
<br />
<i><?=$count;?> <?=$lang['attractions']['totalimages'];?></i>
<br />
</div>
how can i fix this? thanks :)

Check count before entering foreach:
$globs = glob("attractions/$cat/*.jpg");
if( $globs ){
foreach ($globs as $filename) {
$count++;
$files[] = $filename;
$filename = urlencode($filename);
}
}

It seems that you need scandir instead of glob, as glob can't see unix hidden files.
<?php
$pid = basename($_GET["prodref"]); //let's sanitize it a bit
$dir = "/assets/$pid/v";
if (is_dir_empty($dir)) {
echo "the folder is empty";
}else{
echo "the folder is NOT empty";
}
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
return (count(scandir($dir)) == 2);
}
?>
Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An
a === b
expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values
Please check this answer of Your Common Sense for more details

Related

echo text if .php extentin exists in a folder using a php script

im trying to make a php script that if a .php extention exists in a folder it says check mail, if no .php files exist no mail either one or the other results show up not both.
<?php
$directory = "http://server1.bioprotege-inc.net/roleplay_realm_online/contact_us_files/";
if (glob($directory . "*.php") != true) {
echo 'Check Mail:';
}
else {
echo 'No mail Today';
}
?>
that what I got but it aint working it only shows the same result if there is a .php file in the folder or not
The glob() function returns the array of files name with extension so you can not check them with true and false.
Check the reference site: glob function in php
That's why you should use following code to check it:
<?php
$directory = "http://server1.bioprotege-inc.net/roleplay_realm_online/contact_us_files/";
// Open a known directory, and proceed to read its contents
if (is_dir($directory)) {
$arr = array();
if ($dh = opendir($directory)) {
while (($file = readdir($dh)) !== false) {
$arr[] = $file;
}
$name = implode($arr);
if(strstr($name,".php")){
echo "Check Mail:";
} else {
echo "No mail Today";
}
closedir($dh);
}
}
?>
This will be helpful to you. I hope so.
Understanding the risk, this is how it can be done
$dir="core/view/";
if(glob($dir . "*.php")!=null)
echo " New Mail";
else
echo "No Mail";
You can use glob if you have less than a 100k files, else you may get a Allowed memory size of XYZ bytes exhausted ..." error.
In that case you can change the setting in php.ini or you can use
readdir()
You can use readdir() in this manner
if ($handle = opendir('core/view')) {
$flg=0;
while (false !== ($entry = readdir($handle))) {
if(strcasecmp(pathinfo($entry, PATHINFO_EXTENSION),"php")==0){
$flg=1;
break;
}
}
echo $flg;
closedir($handle);
}

deleting images by clicking correspondent buttons

I have a folder / directory containing lots of images and other folders / directories.
I am showing the preview of these files using following code:
<?php
$images=array();
$dir_handler = opendir('test') or die("Unable to open path");
$i=0;
while($file = readdir($dir_handler))
{
if(is_dir($file))
continue;
else if($file != '.' && $file != '..' && $file != 'index.php')
{
$images[$i]=$file;
$i++;
}
}
sort($images);
for($i=0; $i<sizeof($images); $i++)
{
echo "<img style='border:1px solid #666666; width:100px;height:100px; margin: 10px;' src='test/".$images[$i]."'/><input type='button' value='nok[]'>";
} closedir($dir);
?>
The problem is that I want to assign a separate button to each file (to each image or folder), So that by clicking each button, its corresponding image (or folder / directory) gets deleted from the main folder and no more being shown as a preview.
Another small problem is that the preview of folders are not being shown with the above code. Why? Any help will be appreciated.
There are several questions here.
First question: Why won't preview of folders show? This is because you show previews by looping through the $images array, but you do not add directories to that array (see your code where you check if it is_dir and then invoke "continue;"). If you want to include the directories, then you should include them in the $images array (or do something else with them).
Second question: How to do the deleting? You need to either extend your existing PHP script or write another one. You would create a link on the delete icon; the link's href would be to the new (or existing) PHP script and you would pass in as parameters the folder or file to be deleted. If it is a folder, then use rmdir(). If it is a file, then use unlink(). I can help you more with this later, if you need it.
You are always displaying an image, you need to do a check if the $images array value is an image or a folder. Then do something different with the display.
To delete a file or folder, use these functions respectively:
unlink();
rmdir();
http://www.php.net/manual/en/function.rmdir.php
http://php.net/manual/en/function.unlink.php
To add a list of folders before your images change your code to:
<?php
$images=array();
$folders = array();
$dir_handler = opendir('test') or die("Unable to open path");
$i=0;
while($file = readdir($dir_handler))
{
if(is_dir($file)) {
$folders[count($folders)] = $file;
}
else if($file != '.' && $file != '..' && $file != 'index.php')
{
$images[$i]=$file;
$i++;
}
}
sort($images);
foreach($folders as $folder){
echo "<a href='#'>$folder</a>";
}
for($i=0; $i<sizeof($images); $i++)
{
echo "<img style='border:1px solid #666666; width:100px;height:100px; margin: 10px;' src='test/".$images[$i]."'/><input type='button' value='nok[]'>";
}
closedir($dir);
?>
Then all you have to do is build out the visual elements of a folder in your view and link to a function that will do your unlink() and rmdir() where needed.

Listing and linking files that are larger than X by creation date in PHP

I am listing files and linking them using php on a set of static HTML pages with the following script:
<?php
$dir="./content"; // Directory where files are stored
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
//this kills the annoying .. and . directory listing
if($filename == ".." || $filename == ".") continue; ?>
<p><?php echo $filename; ?></p>
<?php
}
closedir($dir_list);
}
?>
What I would like to do now is list files that are larger than a certain file size (i.e. files larger than 35 bytes) and order them by creation date (newest to oldest).
Your help and expertise would be greatly appreciated. Apologies in advance about the code formatting.
Use filesize() to check the size of the file and filectime() to get the creation date. Hope that gives you some direction.
if(filesize($filename) >= YOUR_LIMIT){
//show file
}
To sort, you could insert all files into an array. Something like this:
while(($filename = readdir($dir_list)) !== false){
$arr[filectime($filename)] = $filename;
}
Then sort with ksort():
ksort($arr);
Then loop them out:
foreach ($arr as $value){
echo $value;
}

Using PHP to display a folders contents, but show a message when folder is empty

I'm creating a intranet for my workplace and have used a bit of php I found online to scan the contents of the folder it's in and display them as links. It does this fine, but when it's inside an empty folder I would like it to display a message such as "There are no records matching those criteria.".
Is there a way to add something to the php to specify if there are no folders listed print this?
I have next to no knowledge of php, but html and css are no problem.
Here's the php I'm using in the page:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
closedir($dir);
sort($files);
foreach ($files as $file)
print "<div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
?>
If you need anymore code such as the full page html or css just let me know.
Thanks in advance for any help.
EDIT:
After trying Josh's solution it pretty much nailed it, but I'm now getting "No files found" printing 3 times. Here's the code I'm using now:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if( count($files) == 0 )
{
echo '<p>No files found</p>';
}
else
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
}
closedir($dir);
sort($files);
foreach ($files as $file)
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
?>
Just do an:
if( count($files) == 0 )
{
echo '<p>No files found</p>';
}
else
{
// you have files
}
You can use the count function to check if there are any files in your files array like this:
if(count($files) > 0) // check if there are any files in the files array
foreach ($files as $file) // print the files if condition is true
print " <a href='$file'>$file</a> <br />";
else
echo "ERROR!";
EDIT:
You can also use the scandir function. However, this function will return two extra entries for the current directory and directory up one level. You need to remove these entries from the files array. Your code will look like this:
<?php
$dir = "."; // the directory you want to check
$exclude = array(".", ".."); // you don't want these entries in your files array
$files = scandir($dir);
$files = array_diff($files, $exclude); // delete the entries in exclude array from your files array
if(!empty($files)) // check if the files array is not empty
{
foreach ($files as $file) // print every file in the files array
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
}
else
{
echo "There are no files in directory"; // print error message if there are noe files
}
?>
Try This:
<?php
$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "A.php")
{
array_push($files, $file);
}
}
closedir($dir);
if(count($files) == 0){
die("There are no records matching those criteria.");
}else{
sort($files);
foreach ($files as $file)
print " <div class='fileicon'>
<a href='$file'>
<img src='../../../images/TR-Icon.png'>
<p class='filetext'>$file</p>
</a>
</div>";
}
?>
You can use a simple conditional using count on your file array.
// ...
closedir($dir);
if (count($files) > 0) {
// sort files and iterate through file array, printing html
} else {
echo "There are no records matching those criteria.";
}
// ...
I think you could let it print something else if($files.length == 0) and only print it normally if($files.length > 0) or something.
I have no knowledge of php, but I know java, html, css, and javascript.
I'm sure php has things like array.length (or something else to get the length of an array) in it
I hope this was helpful.
EDIT: I've seen others already answered thigs that are like 10x better than mine.
Also, php seems pretty cool, I might learn it

Read File Names From folder Only Keep Files with .iso extention

I have a script that gets a string from a config file and based on that string grabs the file names of a folder.
I now only need the iso files. Not sure if the best way is to check for the .iso string or is there another method?
<?php
// Grab the contents of the "current.conf" file, removing any linebreaks.
$dirPath = trim(file_get_contents('current.conf')).'/';
$fileList = scandir($dirPath);
if(is_array($fileList)) {
foreach($fileList as $file) {
//could replace the below if statement to only proceed if the .iso string is present. But I am worried there could be issues with this.
if ($file != "." and $file != ".." and $file != "index.php")
{
echo "<br/><a href='". $dirPath.$file."'>" .$file."</a>\n";
}
}
}
else echo $dirPath.' cound not be scanned.';
?>
If you only need the files with an extension of .iso, then why not use:
glob($dirPath.'/*.iso');
rather than scandir()
try this:
if(is_array($fileList)) {
foreach($fileList as $file) {
$fileSplode = explode('.',$file); //split by '.'
//this means that u now have an array with the 1st element being the
//filename and the 2nd being the extension
echo (isset($fileSplode[1]) && $fileSplode[1]=='iso')?
"<br/><a href='". $dirPath.$file."'>" .$file."</a>\n":'');
}
}
If you want it in an OOP style you could use:
<?php
foreach (new DirectoryIterator($dirPath) as $fileInfo) {
if($fileInfo->getExtension() == 'iso') {
// do something with it
}
}
?>

Categories