Checking if thumbnail exists in PHP - php

My directory structure looks like that.
...photo-album1/
...photo-album1/thumbnails/
Lets say we have image1.jpg inside photo-album1/. Thumbnail of this file is tn_image1.jpg
What I wanna do is to check every file inside photo-album1/ if they have thumbnail in photo-album1/thumbnails/. If they have just continue if not, send file name to another function : generateThumb()
How can I do that?

<?php
$dir = "/path/to/photo-album1";
// Open directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
// Walk through directory, $file by $file
while (($file = readdir($dh)) !== false) {
// Make sure we're dealing with jpegs
if (preg_match('/\.jpg$/i', $file)) {
// don't bother processing things that already have thumbnails
if (!file_exists($dir . "thumbnails/tn_" . $file)) {
// your code to build a thumbnail goes here
}
}
}
// clean up after ourselves
closedir($dh);
}
}

$dir = '/my_directory_location';
$files = scandir($dir);//or use
$files =glob($dir);
foreach($files as $ind_file){
if (file_exists($ind_file)) {
echo "The file $filexists exists";
} else {
echo "The file $filexists does not exist";
}
}

The easy way is to use PHP's glob function:
$path = '../photo-album1/*.jpg';
$files = glob($path);
foreach ($files as $file) {
if (file_exists($file)) {
echo "File $file exists.";
} else {
echo "File $file does not exist.";
}
}
Credit to soul above for the basics. I'm just adding glob to it.
EDIT: As hakre points out, glob only returns existing files, so you can speed it up by just checking to see if the filename is in the array. Something like:
if (in_array($file, $files)) echo "File exists.";

Related

Require to display limited number of file names from directories -php

For the below code I have multiple directories and files. I can display one filename per directory(Which is good with the "BREAK").
<?php
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
break;
//---- if ($i>=5) { break; }
}
closedir($dh);
}
}
?>
With
if ($i>=5) { break; } I can still display 5 filenames but it reads only one directory.
I want to display at least 5 file names from all directories, how can I do it?
Use the scandir function.
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
or
If you are using unix you could also do a system call and run the following command.
ls /$dir | head -5
$dir is the directory and -5 is the number filenames in the directory.
Since you said that you have multiple directory's, I rewrote your code a bit:
(Here I first loop through all directory's with array_map() then I get all files from each directory with glob(). After this I just limit the files per directory with array_slice() and at the end I simply print all file names)
<?php
$directorys = ["images/", "xy/"];
$limit = 3;
//get all files
$files = array_map(function($v){
return glob("$v*.*");
}, $directorys);
//limit files per directory
$files = array_map(function($v)use($limit){
return array_slice($v, 0, $limit);
}, $files);
foreach($files as $directory) {
echo "<b>Directory</b><br>";
foreach($directory as $file)
echo "$file<br>";
echo "<br><br>";
}
?>
You don't have to break it, you can just skip it. And in doing so, you have to use continue instead.
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
}
closedir($dh);
}
}
Here is also another scenario. Because you mentioned that you have many directories but you only show one main directory, I am guessing that the directories you've mentioned were inside the /images/ directory.
$dir = "images/";
$i=1;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$j=1;
if (is_dir($file)) {
if ($internalDir = opendir($file)) {
while (($internalFile = readdir($internalDir)) !== false) {
echo $file."->filename: ".$internalFile."<br>";
if ($j>=5)
continue;
$j++;
}
closedir(opendir($file));
}
} else {
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
$i++;
}
}
closedir($dh);
}
}
Read more about continue here: http://php.net/manual/en/control-structures.continue.php

Echo all the folder names in a folder

I want to print all the folder names inside a parent folder. The current issue I am facing is, though I have 400+ folders in a folder only 257 are getting printed. Again, this is not at all issue related with permissions.
Please find my code below:
$newdir = "content/";
$dircnt = 0;
// Open a known directory, and proceed to read its contents
if (is_dir($newdir)) {
if ($dh = opendir($newdir)) {
while (($file = readdir($dh)) !== false) {
$dircnt++;
if(filetype($newdir. $file) == 'dir') {
echo "filename: $file : filetype: " . filetype($newdir. $file) . "dircnt:" .$dircnt. "<br>";
}
}
closedir($dh);
}
}
}
You can use glob() function - returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
$filesDirectories = glob($newdir.'*', GLOB_BRACE);
foreach($filesDirectories as $key=>$file) {
echo "$file size " . filesize($file) . "\n";
}
I would use glob:
$newdir = "content/";
$dirs = glob($newdir.'*',GLOB_ONLYDIR);
foreach($dirs as $index=>$dir){
echo "filename ". $dir." filetype ".filetype($newdir.$dir)." dircnt:".($index+1)."<br/>";
}

how to delete a file from folder in php

I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt.
I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
Initially the folder should have 777 permissions
$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
or try
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
http://php.net/manual/en/function.unlink.php
There is one bug in your code, you haven't given the correct path
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($dir."/".$file);//give correct path,
}
}
closedir($dirHandle);
?>
unlink
if($file==$data) {
unlink( $dir .'/'. $file);
}
It's very simple:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);
try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
rename($old, $new) or die("Unable to rename $old to $new.");

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

php directory read and delete existing files

I am trying to make sure that when the user uploads a profile picture, there can only be one image within the dir "profile_pic". I am openning and reading the dir with a while loop but the #unlink is not working. Below is the php code:
$directory = "uploads\\".$id."\images\profile_pic\\";
if (glob($directory . "*.jpg") != false) {
$filecount = count(glob($directory . "*.jpg"));
if ($filecount > 0) {
//delete exiting pics in folder profile_pic
$handle = opendir($directory);
while ($handle && ($file = readdir($handle)) !== false) {
if ( unlink($entry)) {
$msg .= "File Deleted";
}
}
closedir($directory);
}
}
Sorry, where did you define $entry - did you ever assign a value to it? And why do you make exactly the same call to glob() twice instead of catching the result of the first call in a variable? And why bother to opendir() to list files when you have already glob()ed and obtained that list of files? Especially when you don't apply the same *.jpg filter to the files you are deleting...
Just do this:
// Forward slashes work on Windows too (in PHP, at least)
$directory = "uploads/".$id."/images/profile_pic";
if (($existing = glob($directory . "/*.jpg")) !== false) { // Get a list of files...
foreach ($existing as $file) { // ...loop them...
$msg .= (unlink($directory."/".$file)) ? "File $file deleted\n" : "Could not delete $file\n"; // ...and delete them
}
} else $msg .= "Listing directory failed\n";

Categories