PHP -slim catch uploaded file exception - php

I am using slim to upload files like the following :
foreach ($files as $file) {
try {
$fileLog = $file->moveTo($location));
}
catch(\Exception $e) {
throw new \Exception($e->getMessage());
}
}
return true;
the problem i that there is probably a runtimeexception when there is no space in the disk and the phph trying to save the file.
I am looking for a way to always catch any exception with saving file :
no sapce, broken file ...etc
for now the issue is I cannot catch the runtime exception

Related

Check if the files have been uploaded to server with php slim 3

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.

Laravel 5.3 Intervention/image NotReadableException using images from urls

How do I deal with the following error so that my script doesn't stop working when the exception occurs:
NotReadableException in AbstractDecoder.php line 302: Image source not
readable
I've tried using the following ($file is the url of the image):
// Return false if error
try
{
$img = Image::make($file);
}
catch(NotReadableException $e)
{
return false;
}
This doesn't seem to catch the exception and return false. What else can I do?
You either need the full namespaced exception in the catch area or add the use statement for that exception at the top of the file
Add Intervention\Image\Exception\NotReadableException:
use Intervention\Image\Exception\NotReadableException;
try {
//
} catch(NotReadableException $e) {
//
}

How to catch exceptions in entity?

I have a method in my entity with #ORM\PostRemove() which removes an associated file.
I wonder if I should do something like this:
try {
unlink($file);
} catch (\Exception $e) {
// Nothing here?
}
Does it make sense to catch an exception and do nothing in catch block? Or maybe I shouldn't catch exception here, but then, where should I do it? Should it be an exception from LifecycleCallback method?
I've read here that I shouldn't use logger in entity, so I'm confused what to put there instead.
Your entity shouldn't really contain business logic for your application, its purpose is to map objects to the database records.
The way to approach this depends on the application, for example if you have a File Controller and a removeAction within then the best place to remove the file would likely be here.
As an example: (psuedo code)
public function removeAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$file = $em->getRepository('FileBundle:File')->find($id);
if (!$file) {
throw $this->createNotFoundException('No file found for id '.$id);
}
$filePath = $file->getPath();
if (file_exists($filePath) {
try {
unlink($filePath);
}
catch(Exception $e) {
// log it / email developers etc
}
}
$em->remove($file);
$em->flush();
}
You should always add error checking and reporting in your application, check that a file exists before you attempt to remove it.

Error Handling with files in PHP

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!

Continue the execution code after a Fatal Error

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

Categories