I am trying to catch the exception while uploading file in zend framework 1.
I denied permission to the folder and then ran the following code to catch the exception but it is not working.
public function uploadImage($postedFile,$destination) {
try {
$imageName = $this->getFileName($postedFile); //$postedFile is same as $_FILES
$upload = new Zend_File_Transfer();
foreach ($upload->getFileInfo($imageName) as $info) {
if ($info['name'] != '') {
$ext = pathinfo($info['name'], PATHINFO_EXTENSION);
$newName = md5(rand(1, 100).date('ymdhis') . $info['name']) . '.' . $ext;
$upload->addFilter('Rename', $destination."/".$newName);
if (!$upload->receive($info['name'])) {
return FALSE;
}
}
break;
}
return $newName;
} catch (Zend_File_Transfer_Exception $e) {
throw new Exception('I want to catch this');
}
}
error:
Warning:
move_uploaded_file(/var/www/html/glistonapp/application/../public/images/app_user_profile_picture/80d55d25c52ef4d74079cfa903288b77.png):
failed to open stream: Permission denied in /var/www/html/glistonapp/library/Zend/File/Transfer/Adapter/Http.php on line 189
Warning: move_uploaded_file(): Unable to move '/tmp/phpOtOLVv' to '/var/www/html/glistonapp/application/../public/images/app_user_profile_picture/80d55d25c52ef4d74079cfa903288b77.png' in /var/www/html/glistonapp/library/Zend/File/Transfer/Adapter/Http.php on line 189
It doesn't appear that the methods you are calling on the Zend_File_Transfer object will throw an exception.
Without a thrown exception, you won't be able to "catch" anything in your try block. Instead, you should check the return values of the functions you are calling to determine if there was a problem.
See the API reference which will tell you which methods throw exceptions:
http://framework.zend.com/apidoc/1.12/classes/Zend_File_Transfer_Adapter_Abstract.html
Your error message is not an exception, therefore it won't be caught by the try/catch block.
You should set the appropriate permissions on the destination directory for that error message.
Related
I'm trying to find out whether a blob exists or not. When the blob does not exist, my try-catch with Azure's ServiceException isn't being caught at all. I tried following the steps from here.
public function checkBlobExists($path) {
$container = config('azure.storage.container');
$blobClient = ServicesBuilder::getInstance()->createBlobService(config('azure.storage.connection_string'));
try {
$blob = $blobClient->getBlob($container, $path);
return true;
} catch (ServiceException $e) {
return false;
}
return false;
}
This is some of the error stack:
ServiceException in ServiceRestProxy.php line 491:
Fail:
Code: 404
Value: The specified blob does not exist.
details (if any): .
in ServiceRestProxy.php line 491
at ServiceRestProxy::throwIfError(object(Response), array('200', '206')) in ServiceRestProxy.php line 409
at ServiceRestProxy->MicrosoftAzure\Storage\Common\Internal\{closure}(object(ClientException)) in Promise.php line 203
You may not be using the fully qualified exception class name. Try:
//...
} catch (\MicrosoftAzure\Storage\Common\Exceptions\ServiceException $e) {
//...
}
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) {
//
}
I don't exactly know how exceptions work. as I assume, they should avoid php errors and display "my error message". for example, i want to open file
class File{
public $file;
public function __construct($file)
{
try{
$this->file = fopen($file,'r');
}
catch(Exception $e){
echo "some error" . $e->getMessage();
}
}
}
$file = new File('/var/www/html/OOP/texts.txt');
it works. now I intentionally change the file name texts.txt to tex.txt just to see an error message from my catch block, but instead, php gives an error Warning: fopen(/var/www/html/OOP/texts.txt): failed to open stream: No such file or directory in /var/www/html/OOP/file.php on line 169 . so it's php error, it doesn't display error message from catch block. What am I doing wrong? how exactly try/catch works?
From the PHP manual
If the open fails, an error of level E_WARNING is generated. You may
use # to suppress this warning.
fopen returns FALSE on error so you could test for that and throw an exception which would be caught. Some native PHP functions will generate exceptions, others raise errors.
class File{
public $file;
public function __construct($file){
try{
$this->file = #fopen($file,'r');
if( !$this->file ) throw new Exception('File could not be found',404);
} catch( Exception $e ){
echo "some error" . $e->getMessage();
}
}
}
i am using imagecreatefromstring and currently validate for proper image file format.
So a link of:
swqkdwfibqwfwf
Wont work, because its not a valid file type. But i have just discovered this:
sibdlsibiwbifw.png
Will send without an error from my validation. I get this error for an image link that doesnt return and image:
Warning: file_get_contents(etwteet.png): failed to open stream: No such file or directory in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141
Warning: imagecreatefromstring(): Empty string or invalid image in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 141
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /var/www/clients/client2/web3/web/process/addnewbuild.php on line 143
Is there a way i can catch this error so i can stop the code processing and also notify the user?
Code used to get the URL:
$imagefile = image url;
$resource = imagecreatefromstring(file_get_contents($imagefile));
Thanks. Craig.
With all implementable validations, I believe it is finally required to capture error on imagecreatefromstring.
With an error handler...
The following syntax is supported on PHP 5.3 or later.
set_error_handler(function ($no, $msg, $file, $line) {
throw new ErrorException($msg, 0, $no, $file, $line);
});
try {
$img = imagecreatefromstring(file_get_contents("..."));
} catch (Exception $e) {
echo $e->getMessage();
}
With # and error_get_last...
if (!$img = #imagecreatefromstring(file_get_contents("..."))) {
$e = error_get_last();
die($e['message']);
}
The following syntax is supported on PHP 5.4 or later.
if (!$img = #imagecreatefromstring(file_get_contents("..."))) {
die(error_get_last()['message']);
}
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!