I am trying to use this simple bit of code to iterate through the "export" folder and delete files older than 24 hours:
if ($handle = opendir("/home/username/public_html/en/graphs/export")) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($file);
if((time() - $filelastmodified) > 24*3600)
{
unlink($file);
}
}
closedir($handle);
}
Some notes:
1) I do realize there are similar questions, but the solutions suggested there don't seem to work for me.
2) The absolute path to the directory is correct (tested)
3) The directory has 777 permissions. The files in it don't, but I tested with some files with 777 permissions and the same errors happened. So it doesn't seem to be a permission issue.
4) The file that contains this code is in a different directory (it's a cron job, I like to keep them together in a separate directory)
This is the error that appears (for each file in the directory):
Warning: filemtime() [function.filemtime]: stat failed for countries_rjRp9.png in /home/username/public_html/path-to-crons/crons/exports.php on line 12
Warning: unlink(countries_rjRp9.png) [function.unlink]: No such file or directory in /home/username/public_html/path-to-crons/crons/exports.php on line 16
In this example, countries_rjRp9.png is one of the files that should be unlinked from the export directory.
What's going on here?
You should specify the full path to unlink the file. In your loop, $file will be countries_rjRp9.png and you're trying to unlink it from the working directory, which is, the directory in which all of your cronjobs reside.
You state that the absolute path to your files is correct, but you forgot to use the absolute path once you're in your loop. You're only using an absolute path in your opendir() call, nowhere else.
Try doing something like this:
if ($handle = opendir("/home/username/public_html/en/graphs/export")) {
while (false !== ($file = readdir($handle))) {
// Take the filename and add its full path
$file = "/home/username/public_html/en/graphs/export/" . $file;
$filelastmodified = filemtime($file);
if((time() - $filelastmodified) > 24*3600)
{
unlink($file);
}
}
closedir($handle);
}
Related
Below is my attempt to delete a folder and all its content. A folder may contain zip files and folders with files.
public function deleteFolder($dir){
if(file_exists($dir)){
$it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
$files = new \RecursiveIteratorIterator($it,
\RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
}
}
but it returns the following error:
rmdir(C:\Juliver\UIUX\pd-loader\loader/temp/utso-pulgada-pd-loader-5066a7e0298a):
Directory not empty in C:\Juliver\UIUX\pd-loader\loader\Patcher.php on line 95
line 95 points to rmdir($dir); line
If I check the folder utso-pulgada-pd-loader-5066a7e0298a, I see that it's already empty but it throws me the above error.
$dirname = 'C:/Users/Admin/Desktop/test';
array_map('unlink', glob("$dirname/*.*"));
rmdir($dirname);
try this, this remove all the file present in the folder, and that folder too
Directory may contain other directories so you have to use a recursive function.
function removeDir($path) {
$files = glob("$path/*");
foreach ($files as $file) {
if (is_dir($file)) {
removeDir($file);
} else {
unlink($file);
}
}
rmdir($path);
}
Now is enough to call removeDir("/my/nice/path");
If you see the directory already empty, try to check for hidden files and be sure that you have the right permissions.
I suspect you have already checked its not a file permissions issue. As your code works for me but not you, it makes me wonder if it is a to do with PHP file stat or Real Path caching.
Unlinking a file should clear stat cache for individual file automatically. However PHP bugs have previously been known to cause this issue with rmdir.
Try doing a clearstatcache after the rmdir statement in your foreach block.
Previously I've used glob (mentioned in other answers) so I've no idea how RecursiveDirectoryIterator works re file handles; as a long shot try destroying these objects ( unset($files); unset($it) ) before your final rmdir.
What i am trying to do is to delete all files in my target servers folder, the folder all the files are in is: "/public_html/" this directory contains all the target files, i don't want to delete this folder as it must remain the intact, just everything inside.
function ftpDelete($conn, $directory) {
echo "<pre><b>FTP Files on Server:</b>\n";
$filelist = ftp_nlist($conn, $directory);
foreach($filelist as $file) {
// Do not show "." or ".."
if ($file != "." && $file != "..") {
ftp_delete($conn, $directory);
echo $file . "\n";
}
}
echo "</pre>";
}
// Run delete functions ...
ftpDelete($conn, "/public_html/");
// Files out that is still on the server ...
FTP Folders on Server:
/public_html/vendor
/public_html/stats
/public_html/icon
/public_html/images
This code so far will delete all files that is the "public_html" directory, but not any folders, i know from reading the folders need to be empty first, i'm not sure the best way to handle these folders, i didn't see a command that would delete the target folders and it's contents, any help would be appreciated.
You need to append the filename after the directory:
ftp_delete($conn, "$directory/$file");
I am having issue with automatically deleting files from a specific folder on my server.
I need to run an automatic delete every 31 mins on a folder which stores incoming documents. These files will always be *.pdf format.
I have found an issue similar on this site.
How to delete files from directory based on creation date in php?
However my issue is with *.pdf files and I have never used php before, ideally I was looking for a .bat file, but if that's not possible it's no problem.
<?php
if ($handle = opendir('/path/to/files')) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($file);
if((time() - $filelastmodified) > 24*3600 && strtolower(substr($file, -4)) == ".pdf")
{
unlink($file);
}
}
closedir($handle);
}
?>
This added condition checks if the filename ends with ".pdf". You could run this as a cronjob.
You might as well use shell commands instead. find with -name, -exec and -mtime does the same and saves the need for a PHP parser.
Am a beginner in php. My problem is, i use the following code to create a directory and copy some files into it(I used a code get from so itself). The code works fine directory is created and files are copied. But I am getting a warning like this.
function copyr($source, $dest)
{
// Simple copy for a file
if (is_file($source)) {
chmod($dest, 0777);
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
}
chmod($dest, 0777);
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
copyr("agentSourcefolder", "testTemp5");
.
Warning: chmod() [function.chmod]: No such file or directory in /home/websiteName/public_html/php_file_upload2.php on line 9
I have to get the response from server after this, what should i do? I used
header("Location: http://www.websiteName.com/");
But it shows the following error
Warning: Cannot modify header information - headers already sent by (output started at /home/websiteName/public_html/php_file_upload2.php:9) in /home/websiteName/public_html/php_file_upload2.php on line 41
And if the directory is already created this code works fine
This one:
Warning: Cannot modify header information - headers already sent by (output started at /home/websiteName/public_html/php_file_upload2.php:9) in /home/websiteName/public_html/php_file_upload2.php on line 41
is because you are passing the header('location:') call after anything has been written to the screen. All of this processing should be done before anything is written to the page, like echo, breaking out of php, etc. Also make sure there's NO white space before the opening <?php line.
The other error is likely because a file you're trying to chmod doesn't exist or exist yet. Or that you may need to provide an absolute path to mkdir. like $_SERVER['DOCUMENT_ROOT']."/path-to-new-dir/"
Why do I get this error even though the directory exists? it works fine if I target the parent directory, I tried using %20 instead of space too, and tried removing the last / but nothing works!
Warning: opendir(/home/xxxx/user_files/users/xxxx/test directory/) [function.opendir]: failed to open dir: No such file or directory in /home/xxxx/public_html/beta/stream._pages/file._list._i.php on line 54
(Note: xxxx is just me censoring user names)
Make a file called test.php and put it in your test directory. In that file, put this code:
<? echo dirname(__FILE__);?>
Then, visit test directory/test.php in your web browser, copy and paste the path as given in test.php and try using that exact path in opendir.
Another issue might be that the permissions of your directory aren't right, try chmodding to 777
For anyone trying to find the folder outside of the public_html folder.
This code is provided by php.net for the opendir() function:
if ( $handle = opendir('../../../../') )
{
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while ( false !== ( $entry = readdir( $handle ) ) )
{
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle))
{
echo "$entry\n";
}
closedir( $handle );
}
Solution
The $handle I started checking out how far I could go back with '../' adding as much ../ as possible until you find yourself in the folder you need. From there you take I guess.
For me '../../../../' was enough to get there, it's different on every server.