My function cleanup looks like that.
function cleanUp($exdirs, $exfiles){
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('.'),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach($it as $entry) {
if ($entry->isDir() && !in_array($entry->getBasename(), $exdirs)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
elseif (!in_array($entry->getFileName(), $exfiles)) {
unlink($entry->getPathname());
}
}
}
And calling this function like that
$excludeDirsNames = array('cgi-bin');
$excludeFileNames = array('ws.zip');
cleanUp($excludeDirsNames , $excludeFileNames);
Now the problem is i'm getting warning message. can not unlink cgi-bin on line unlink($entry->getPathname());
What's wrong with my function? How to fix that problem?
I am guessing that cgi-bin is a symlink and not a regular directory. That's why it's getting into the "unlink" section. The error message is probably due to permissions.
The fix, move 'cgi-bin' to the $excludeFileNames array.
Related
Hi have the following code in slim to save file
I want to make sure the files have been uploaded to the server and only then to return true. or false
how can I do that with Slim or PHP?
Result of file log always null for nonreason and the file are being uploaded
public function saveFiles(Array $files, $location) {
try
{
/** #var UploadedFileInterface $file */
foreach ($files as $file) {
$fileLog = $file->moveTo($location . DIRECTORY_SEPARATOR . $file->getFilename());
}
return true;
}
catch(\Exception $e) {
throw new Exception($e->getMessage());
According to slim implementaion of this PSR, it always throws exception if something went wrong while file is being uploaded.
I don't know whether you throw another Exception for a reason, but you can process it something like:
public function saveFiles(Array $files, $location) {
$result = true;
foreach ($files as $file) {
try {
$fileLog = $file->moveTo($location . DIRECTORY_SEPARATOR . $file->getFilename());
} catch(\Exception $e) {
// Exception on file uploading happened, but
// we still continue loading other files
$result = false;
// Or just `return false;` if you don't want
// to upload other files if exception happened
// return false;
}
}
return $result;
}
Of course, this method can be extended to collect exceptions' messages and return them.
Good day,
I modified this file.
vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php
This is the function I modified.
public function handleError($level, $message, $file = '', $line = 0, $context = [])
I made it send me an email. The email has the $message and the $file and the $line.
This is what the email said.
MESSAGE FILE vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php LINE 126
The message is blank, but it's running into an error in a file. I open the file.
public function delete($paths)
{
$paths = is_array($paths) ? $paths : func_get_args();
$success = true;
foreach ($paths as $path) {
try {
if (! #unlink($path)) { # the error is here
$success = false;
}
} catch (ErrorException $e) {
$success = false;
}
}
return $success;
}
I am confused. Why was the error not caught by the catch block? What type of error would not give a message to the error handler of laravel? Is there something I can do to get more information regarding the error?
This is our version of Laravel.
Laravel Framework version 5.1.45 (LTS)
First of all the question you have asked is misleading. What you are trying to do is add a custom error handler in laravel which you can achieve by following this URL .
The error you are facing might be caused due to file permission error.
And since there is the # sign before the function call unlink() any errors which are caused by it are suppressed.
Remove the # sign and if the file doesn't exists or if there is an error it would throw it and then catch block would catch it.
Error Handling with files in PHP
$path = '/home/test/files/test.csv';
fopen($path, 'w')
Here I want add an error handling by throwing exceptions, on 'No file or directory is found' and 'No permission to create a file'.
I am using Zend Framework.
By using fopen with write mode, I can create a file. But how to handle it when corresponding folder is not there?
i.e if files folder is not present in root structure.
How to throw an exception when no permission is permitted for creating a file?
Something like this should get you started.
function createFile($filePath)
{
$basePath = dirname($filePath);
if (!is_dir($basePath)) {
throw new Exception($basePath.' is an existing directory');
}
if (!is_writeable($filePath) {
throw new Exception('can not write file to '.$filePath);
}
touch($filePath);
}
Then to call
try {
createFile('path/to/file.csv');
} catch(Exception $e) {
echo $e->getMessage();
}
I suggest, you take a look at this link: http://www.w3schools.com/php/php_ref_filesystem.asp
especially the methods file_exists and is_writable
Like this:
try
{
$path = '/home/test/files/test.csv';
fopen($path, 'w')
}
catch (Exception $e)
{
echo $e;
}
PHP will echo whatever error would arise there.
Though you can also use is_dir or is_writable functions to see if folder exists and has permission respectively:
is_dir(dirname($path)) or die('folder doesnt exist');
is_writable(dirname($path)) or die('folder doesnt have write permission set');
// your rest of the code here now...
But how to handle it when corresponding folder is not there?
When a folder does not exist .. try to create it!
$dir = dirname($file);
if (!is_dir($dir)) {
if (false === #mkdir($dir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
}
} elseif (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to write in the %s directory', $dir));
}
// ... using file_put_contents!
I use imagick to create thumbnails of PDF files, but in some cases imagic returns a Fatal Error.
I am looking for a way to know when the fatal error occurs.
Something like this:
function MakeThumb($source) {
if($im = new imagick($source)) {
//Generate thumbnail
return($thumb);
} else {
return 'no_thumb.png'; // then we will not tray again later.
}
}
You could do something like this
function MakeThumb($source) {
try {
//throw exception if can't create file
if(!$im = new imagick($source) {
throw new Exception('Count not create thumb');
}
//ok if got here
return($thumb);
} catch (Exception $e) {
return 'no_thumb.png';
}
}
I haven't tested it,but by using Try Catch, you can make it work
http://php.net/manual/en/language.exceptions.php
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
echo "$file\n";
}
Is there any way for this code to not throw UnexpectedValueException "failed to open dir: Permission denied" whenever there is a unreadable subdirectory inside directory I attempt to list?
UPDATE
Converting foreach() to while() and explicitly calling Iterator::next() wrapped in try() catch {} doesn't help. This code:
$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
$file = $iter->current();
echo "$file\n";
try {
$iter->next();
} catch(UnexpectedValueException $e) {
}
};
is an infinite loop if there is unreadable subdirectory.
Apparently you can pass $flags parameter to constructor. There's only one flag in the docs, but it does exactly what you want: catches exceptions during getChildren() calls and simply jumps to the next element.
Change your class creation code to
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("."),
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD);
and it should work
You could do something like this :
class ReadableFilter extends RecursiveFilterIterator{
public function accept(){
return $this->current()->isReadable();
}
}
$filteredIterator = new RecursiveIteratorIterator(new ReadableFilter(new RecursiveDirectoryIterator(".")));
foreach ($filteredIterator as $file){
echo "$file\n";
}