php directory read and delete existing files - php

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";

Related

How to fetch the folder names in codeigniter "views" folder

I am trying to get folder names in codeigniters' "views" folder to create a kind of template class that will fetch all folder names in "view"...
I actually want to create a default template for my site and then be able to change it just by adding another template folder like wordpress themes
how do I do that?
If you could hopefully understand what I want to say here...
?php
// declare the folder
$ourDir = "/home/public_html/folderName";
// prepare to read directory contents
$ourDirList = #opendir($ourDir);
// loop through the items
while ($ourItem = readdir($ourDirList))
{
// check if it is a directory
if (is_dir($ourItem))
{
echo "directory: $ourItem <br />";
}
// check to see if it is a file
if (is_file($ourItem))
{
echo "file: $ourItem <br />";
}
}
closedir($ourDirList);
?>
tried this but doesn't work.. :(
Well i just found my ans ...
<?php
$dir = APPPATH.'views/';
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(filetype($dir . $file) == 'dir' && $file != '..' && $file != '.') {
echo "filename: $file : filetype: " . filetype($dir . $file) . "<br>";
}
}
closedir($dh);
}
}
?>
This will echo out all the folders...

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/>";
}

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

Checking if thumbnail exists in 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.";

read files insert text into mysql

myFolderi have thousands of image files that have keyword text for the name. i am trying to read from the list of images and upload the text into a dB field. the problem is that some of the text has utf8 characters like l’Été that show up like this ��t�
how can i read foreign characters so that the accents will insert into the dB field?
this is how im handling it now
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);//$dir = directory name
//array_push($files, $dir);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('../../myDirectory') as $key=>$file){
//$file = preg_replace( '#[^\0-\x80]#u',"", $file );
echo $file ."<br />";
}
this is producing the same result
$str = "l’Été";
utf8_decode($str);
echo $str;
This solution may work for you, it will loop through all files in a directoy and then recursivly through any directories found until it ends up with a massive array of files.
Ive added some points you may wish to change, eg either mutli or single dimension arrays ( all depend on if you may want to maintain the folder structure.
and also if you want the file extention to be saved when you save the file name to db.
Code
function recursive_search_dir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (in_array($file,array(".","..")))
continue; // We dont want to do anything with parent / current directory.
if (is_dir($file)) {
$result[] = recursive_search_dir($file); // Multi-dimension
# OR
array_merge($result,recursive_search_dir($file));// Single-dimension if you dont care about folder structure.
} else {
$result[] = utf8_decode($file); // full file name ( includes extention )
# OR
$result[] = utf8_decode(filename($file,PATHINFO_FILENAME)); // if you only want to capture the name and not the extention.
}
}
closedir($handle);
}
return $result;
}
$files = recursive_search_dir("."); // recursively searcht the current directory.

Categories