I wanna check if there any image on a folder from my server. I have this little function in PHP but is not working and I don't know why:
$path = 'folder/'.$id;
function check($path) {
if ($handle = opendir($path)) {
$array = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && count > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
}
closedir($handle);
}
Any help will be appreciated, thanks in advance.
It does not work because count is coming from nowhere. Try this instead:
$path = 'folder/'.$id;
function check($path) {
$files = glob($path.'/*');
echo empty($files) ? "$path is empty" : "$path is not empty";
}
Try this function: http://www.php.net/glob
Try This:
$path = 'folder/'.$id;
function check($path) {
if (is_dir($path)) {
$contents = scandir($path);
if(count($contents) > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
closedir($handle);
}
It counts the contents of the path. If there are more than two items, then its not empty. The two items we are ignoring are "." and "..".
Step 1: $query = select * from your_table where id=$id;
Step 2: $path=$query['path_column'];
Step 3: if($path!=null&&file_exit($path)&&$dir=opendir($path)){
while (($file = readdir($dir )) !== false)
{
if ($file == '.' || $file == '..')
{
continue;
}
if($file) // file get
{
$allowedExts = array("jpg");
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($extension, $allowedExts))
$file[]=$file;
}
$data[file_name'] = $file;
}
closedir($dir);
}
Related
I want to copy images from one folder to another on server, now I use this code:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$list[] = $file;
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
But I need to copy just images selected by time - for example images uploaded between "now" and 5 min. ago..
Can anyone help?
Thanks
Now my PHP is like below. It seems that it run with "Done" result, but nothing is copied..
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder'.$file;
if (file_exists($fpath)) {
if($file != "." && $file != ".." &&
DateTime::createFromFormat('U', filemtime($file)) < new DateTime("-5
minutes"))
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
So this is my code, that works for me well - copy images between folders according to time (- 5 sec) set by other code in "time.txt" file:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder/'.$file;
if (file_exists($fpath)) {
$subor = fopen("./time.txt", "r");
$cas_txt=fgets($subor, 11);
fclose($subor);
$cas_zac = DateTime::createFromFormat('U', $cas_txt)->modify('-5 seconds');
if ($file != "." && $file != ".." && DateTime::createFromFormat('U',
filemtime($fpath)) > $cas_zac)
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
//copy file to new folder
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
I have two more questions:
Please how can I rotate images in 180° by or after copy? Is it possible in one php code?
How can I send multiple files - images from my code - like an attachments by mail in php?
Thanks for your help.
You should use the filemtime function
I'm trying to open a directory, read just files with a .txt format and then display the contents. I've coded it out, but it doesn't do anything, although it doesn't register any errors either. Any help?
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
$entry=array();
while(false!==($file = readdir($handle))) {
if ( !strcmp($file, ".") || !strcmp($file, "..")) {
}
else if(substr($file, -4) == '.txt') {
$entry[] = $file;
}
foreach ($entry as $txt_file) {
if(is_file($txt_file) && is_writable($txt_file)) {
$file_open = fopen($txt_file, 'r');
while (!feof($file_open)) {
echo"<p>$file_open</p>";
}
}
}
}
Help is quite simple.
Instead
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
write (I am sorry for re-formatting of new lines)
$dir = 'information';
if(is_dir($dir))
{
$handle = opendir($dir);
}
else
{
echo "<p>There is a system error</p>";
}
because if has to be written only smallcaps, thus not If.
And the second part rewrite to (again, you may use your own formatting of new lines)
$entry=array();
$file = readdir($handle);
while($file !== false)
{
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
foreach ($entry as $txt_file)
{
if(is_file($txt_file) && is_writable($txt_file))
{
$file_open = fopen($txt_file, 'r');
while(!feof($file_open))
{
echo"<p>$file_open</p>";
}
}
}
}
because PHP has elseif, not else if like JavaScript. Also I separated $file = readdir($handle) for possible source of error.
Code part
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
should be shortened only to
if(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
because when if part is empty, then it is not neccessary.
That is all I can do for you at this time.
Instead of iterating the directory with readdir, consider using glob() instead. It allows you to specify a pattern and it returns all files that match it.
Secondly, your while loop has an error: you conditionally add the file name to the list of files, but then you always print every file name using a foreach loop. On the first loop it will print the first file. On the second loop it will print the first and second files, etc. You should separate your while and foreach loops to fix that issue (i.e. unnest them).
Using glob, the modified code will look like:
$file_list = glob('/path/to/files/*.txt');
foreach ($file_list as $file_name) {
if (is_file($file_name) && is_writable($file_name)) {
// Do something with $file_name
}
}
So I'm creating an image upload site and I need to delete multiple directories and files simultaneously. I have managed to create code that does the job however I'm unsure whether this is 'good code' as I'm repeating myself.
Is there a better way to write the below?
$dirname = 'uploads/'.$album_id;
$dirnamethumb = 'uploads/thumbs/'.$album_id;
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
if (is_dir($dirnamethumb))
$dir_handle = opendir($dirnamethumb);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirnamethumb."/".$file))
unlink($dirnamethumb."/".$file);
else
delete_directory($dirnamethumb.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
rmdir($dirnamethumb);
return true;
Thank you in advance for your help!
Why not try this recursive function from similar question
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
} rmdir($dir);
}
try this,
$dir = '/path/to/some/dir/'; // notice: trailing slash!
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (is_dir($dir . $entry) ) {
rmdir($dir . $entry);
}
}
closedir($handle);
}
?>
I'm using php to delete folders containing images of posts that where deleted. I'm using the code below which I found online and does a good job.
I want to know how can I delete only a specific folder in a folder when there are other folders in it.
When I using the code below, how is it possible to do this?
Using: /dev/images/norman/8 -> Will not delete folder 8
Using: /dev/images/norman/ -> Will delete all folders
Eg:
/dev/images/norman/8 -> I need to delete only this folder
/dev/images/norman/9
/dev/images/norman/10
/dev/images/norman/11
/dev/images/norman/12
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/8';
emptyDir($path);
function emptyDir($path) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
?>
<?php
delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
?>
if you are using, version 5.1 and above,
<?php
function deleteDir($dir) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)
{
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
deleteDir("temporary");
?>
You want to hear about rmdir.
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
if(rmdir($path."/".$file)) {
$debugStr .= "Deleted Directory: ".$file."<br />";
}
}
EDIT: as rmdir can only handle empty dirs, you may use this solution as reported in rmdir's page comments:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}
It just recursively deletes everything in $dir, then gets rid of directory itself.
I added an $exclude param to your function, this param it's an array with the names of directories you want to exclude from being deleted, like so:
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/';
emptyDir($path); //will delete all under /norman/
emptyDir($path, array('8')); //will delete all under /norman/ except dir 8
emptyDir($path, array('8','10')); //will delete all under /norman/ except dir 8 and 10
function emptyDir($path,$exclude=false) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
if (!$exclude) {
$exclude = array();
}
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else if (!in_array($file, $exclude)) {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
You can use system commands ex. exec("rm -rf {$dirPath}"); or if you want to do it by PHP you have to go recursive, loops won't do it right.
public function deleteDir($path) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
deleteDir($path."/".$file."/");
rmdir($path."/".$file);
}
}
}
}
}
When I using the code below, how is it possible to do this? Using:
/dev/images/norman/8 -> Will not delete folder 8 Using:
/dev/images/norman/ -> Will delete all folders
I think your problem is that you're missing "/" at the end of "/dev/images/norman/8"
$path='./ggg';
rrmdir($path);
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
I have several files in a directory.I want to display all those filenames with the extension .txt and .jpeg
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo("/etrade/home/collections/utils");
if (($actual_file["extension"]== "txt") ||
($actual_file["extension"]== "jpg") ||
($actual_file["extension"]== "pdf")) {
//Require changes here.Dont know how to iterate and get the list of files
echo "<td>"."\n"." $actual_file['basename']."</a></td>";
}
}
closedir($handle);
}
Please help me on how to iterate and get the list of files .For instance I want all files with jpg extension in a seperate column and pdf files in a seperate column(since I am going to display in a table)
See if this does what you want (EDITED):
<?php
$ignoreFiles = array('.','..'); // Items to ignore in the directory
$allowedExtensions = array('txt','jpg','pdf'); // File extensions to display
$files = array();
$max = 0;
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if (in_array($file, $ignoreFiles)) {
continue; // Skip items to ignore
}
// A simple(ish) way of getting a files extension
$extension = strtolower(array_pop($exploded = explode('.',$file)));
if (in_array($extension, $allowedExtensions)) { // Check if file extension is in allow list
$files[$extension][] = $file; // Create an array of each file type
if (count($files[$extension]) > $max) $max = count($files[$extension]); // Store the maximum column length
}
}
closedir($handle);
}
// Start the table
echo "<table>\n";
// Column headers
echo " <tr>\n";
foreach ($files as $extension => $data) {
echo " <th>$extension</th>\n";
}
echo " </tr>\n";
// Table data
for ($i = 0; $i < $max; $i++) {
echo " <tr>\n";
foreach ($files as $data) {
if (isset($data[$i])) {
echo " <td>$data[$i]</td>\n";
} else {
echo " <td />\n";
}
}
echo " </tr>\n";
}
// End the table
echo "</table>";
If you just want to display two lists of files (it's not clear what part you're having trouble with from your question) can't you just store the filenames in an array?
You don't seem to be getting the file details - you're getting the pathinfo for /etrade/home/collections/utils, but you never add the file name to it.
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo($file);
switch ($actual_file['extension'])
{
case ('jpg'):
$jpegfiles[] = $actual_file;
break;
case ('pdf'):
$pdffiles[] = $actual_file;
break;
}
}
closedir($handle);
}
echo "JPG files:"
foreach($jpegfiles as $file)
{
echo $file['basename'];
}
echo "PDF Files:"
foreach($pdffiles as $file)
{
echo $file['basename'];
}
?>
Obviously you can be cleverer with the arrays, and have use multi-dimensional arrays and do away with the switch if you want.