check if filename is like string in php for displaying images - php

I am trying to get all images from a folder with php. It works fine. Now i wanna check if a certain image exists, and if so don't display it.
This is my basic code with works fine:
foreach (glob("Bilder/Spectrum/*.png") as $filename) {
$filenameDienst = explode("_", $filename);
echo "<a href='Dienste?d=".$filenameDienst[1]."#tabs-2'> <img class='loopimage' src='".$filename."'> </a>";
}
Now i wanna check for the image name "MB_default_Spectrum.png" and if it exists don't display it.
I have tried this:
foreach (glob("Bilder/Spectrum/*.png") as $filename) {
$filenameDienst = explode("_", $filename);
if ($filename != "MB_default_Spectrum.png") {
echo "<a href='Dienste?d=".$filenameDienst[1]."#tabs-2'> <img class='loopimage' src='".$filename."'> </a>";
}
}
But it did not work.. it is still displaying. What is wrong here? Thanks

glob returns an array of the paths matching the given pattern, not just the filenames. Looking at your code, the condition should then be:
if ($filename != "Bilder/Spectrum/MB_default_Spectrum.png")
Also, I personally prefer the following code (I find it cleaner):
$results = glob('path/to/dir/*.png');
foreach ($results as $filename)
// Skip specific file
if ($filename === 'path/to/dir/secretNuclearLaunchCodesAsImage.png')
continue;
echo $filename
}

Related

Where does "." (dot) come from when using PHP ´scandir´

I'm a bit confused.
I'm building a PHP function to loop out images in a specified dir.
PHP
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$thumbnails = scandir($dir);
print_r($thumbnails);
foreach ($thumbnails as $value) {
echo "<img src='".$dir.$value. "'>";
}
array
(
[0] => .
[1] => ..
[2] => bjornc.jpg
[3] => test_bild3.jpg
)
HTML
<img src='bilder/22159/thumbnail/.'>
<img src='bilder/22159/thumbnail/..'>
<img src='bilder/22159/thumbnail/bjornc.jpg'>
<img src='bilder/22159/thumbnail/test_bild3.jpg'>
How can i get rid of theese dots?
I guess it´s the directorie dots..
UPDATE
The most easy way was found in php.net manual
$thumbnails = array_diff(scandir($dir), array('..', '.'));
The dot directory is the current directory. Dot-dot is the parent directory.
If you want to create a list of files in a directory you should really skip those two, or really any directory starting with a leading dot (on POSIX systems like Linux and OSX those are supposed to be hidden directories).
You can do that by simply check if the first character in the file name is a dot, and if it is just skip it (i.e. you continue the loop).
You can skip it by using in_array as
foreach ($thumbnails as $value) {
if (!in_array($value, array(".", ".."))) {
echo "<img src='" . $dir . $value . "'>";
}
}
You can also use this
foreach ($thumbnails as $value) {
if ( $value !='.' && $value !='..')
{
echo "<img src='".$dir.$value. "'>";
}
}
If you are looking for a specific file type, such as images, you are better off using glob.
It allows you to pass a pattern of extensions.
This way you can be sure you fetch only the files you are looking for.
Example for multiple file types, .jpg and .png
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.{jpg,png}", GLOB_BRACE);
print_r($files);
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
Example for a single file type, .jpg
$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.jpg");
print_r($files);
they are directory and parent directory, they can be removed with following code:
<?php
$dir = "downloads/";
if (is_dir($dir)){
if ($dir_handler = opendir($dir)){
while (($file = readdir($dir_handler)) !== false){
if ($file!="."&&$file!="..") {
//your code
}
}
closedir($dir_handler);
}
}
?>
#joachim Pileborg answer is correct, By the way you can also use glob()
$thumbnails = glob("$dir/*.jpg");
foreach ($thumbnails as $value) {
echo "<img src='$value'/>";
}

PHP loop with dyamic images from a folder list

I have a folder called loop-images which has a set of images. I also have the php loop below:
foreach ($feed as $feed_id => $feed_title){
echo '<img src="/loop-images/01.jpg" border="0"><br>';
echo ''.$feed_title.'';
}
In the loop I have a fixed image, However I am looking to use the image dynamically from the loop-images folder. So basically, on the first loop it should use the first image and so on. If it runs out of images in the loop then it starts from the first image again.
Any ideas how I can achieve this?
Thanks
Here is something which you can try
$directory = "/loop-images"; // path to loop images folder
$images = glob($directory . "*.jpg");
$imagescounter = 0; foreach ($feed as $feed_id => $feed_title){
if($imagescounter>count($images)){
$imagescounter = 0;
}
echo '<img src="/loop-images/'.$images[$imagescounter].'.jpg" border="0"><br>';
echo ''.$feed_title.'';
$imagescounter++;
}
Maybe what you're trying to accomplish is something like that.
Using the scandir function and a regex to match all images using preg_match php function
foreach(scandir('/path/to/loop-images/') as $key => $file) {
if (preg_match('/[\s\S]+\.(png|jpg|jpeg|tiff|gif|bmp)/iu', $file)) {
echo '<img src="loop-images/' . $file . '" border="0"><br>';
}
}

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

echoing thumbnails that link to the larger image

I have a script that scans a directory of thumbnails and echoes them to the page. It works nicely, but the thumbnails are not clickable, and i would really like this to be the case. echo "<img src='$thumbnail' class='resizesmall'>"; is the line where the thumbnails are echoed. I'm not sure how to write the path to the larger image inside the php without breaking it. Maybe this should be done inside the foreach statement? thanks for your help?
$dir = "../mysite/thumbnails/";
$dh = opendir($dir);
// echo "$dh";
$gallery = array();
while($filename = readdir($dh))
{
$filepath = $dir.$filename;
//pregmatch used to be ereg
if (is_file($filepath) and preg_match("/\.png/",$filename))
{
$gallery[] = $filepath;
}
}
sort($gallery);
foreach($gallery as $thumbnail)
{
echo "<img src='$thumbnail' class='resizesmall'>";
}
?>
</div>
<??>
The easiest way would be to setup a situation where your thumbs and your full size images were named the same. So you may have thumbs/image1.png and full/image1.png. Then instead of using $thumbnail use a variable $image, or something similar just so the code reads better. You'll also want to leave the $filepath out of the mix so that $image ends up as just the file name.
foreach($gallery as $image)
{
echo "<a href='full/$image'><img src='thumb/$image' class='resizesmall'></a>";
}
You may want to throw in some checks to make sure there is a matching image just to prevent errors or bad UX. However, the code above should work.

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