How to catch invalid image when using PHP imagecreatefromstring - php

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']);
}

Related

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 exception in uploading file - zend framework 1

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.

Warning Error: ftp_get(): Transfer complete. in cakePHP

i am trying to download a zip file from server and save it. i get the following error.
the project is in cakePHP
Downloading /server/biruhxml20140925.zip ...
Warning Error: ftp_get(): Transfer complete. in [(pathprefix)/app/Console/Command/Task/ImportUtilityTask.php, line 214]
//server/biruhxml20140925.zip could not be downloaded to (pathprefix)/files/downloaded_files/bild/biruhxml20140925.zip
biruhxml20140925.zip could not be downloaded as the file is not there yet.
this is the function which makes the call.
public function downloadFTPFile ($remoteFile, $localFile) {
$connection = $this->ftpConnection;
ftp_pasv($this->ftpConnection, true);
$this->out(__('Downloading %s ... ', $remoteFile));
try {
if (ftp_get($connection, $localFile, $remoteFile, FTP_BINARY)) {
$this->out(__('Saved %s', $localFile));
return true;
} else {
$this->out(__('%s could not be downloaded to %s', $remoteFile, $localFile));
return false;
}
} catch (Exception $e) {
#unlink($localFile);
$this->out($e->getMessage());
}
$this->nl();
return false;
}
can anyone suggest a work around to get rid of the warning other then setting debug level 0 in core.php
Have you considered, based on the error message, that the file you try to download is not present on the server?
Your code doesn't do a check if the file is there, I would add that and handle that case accordingly.

fopen() [function.fopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known

$url=$row1['content_url'];
$file_handle = fopen($url,"r");
$line=fread($file_handle,400);
$line1 = wordwrap($line,400,"</br>" );
fclose($file_handle);
the above give is my code for reading data in the text file...
it is working fine in my localhost...
But it is not working in serevr.....
Warning: fopen() [function.fopen]: php_network_getaddresses:
getaddrinfo failed: Name or service not known in
/home/content/08/11968108/html/dev/index.php on line 57
Warning: fread() expects parameter 1 to be resource, boolean given in
/home/content/08/11968108/html/dev/gopi/index.php on line 58
Warning: fclose() expects parameter 1 to be resource, boolean given in
/home/content/08/11968108/html/dev/gopi/index.php on line 60
Make sure the URL in $url contains a wrapper (like http).
Explanation
fopen("www.domain.com","r");
This will look for a local file named www.domain.com
fopen("http://www.domain.com","r");
This will try to get the external file http://www.domain.com (if allow_url_fopen is enabled)
But your error could also indicate an old cached DNS record. If you can, try to change your name server on the production system (e.g.: 8.8.8.8 for the name server from google).
If you just need to handle the warnings that are thrown (as I did), you may just do this to turn them into Exceptions that can be handled:
set_error_handler(
function ($err_severity, $err_msg, $err_file, $err_line, array $err_context) {
// do not throw an exception if the #-operator is used (suppress)
if (error_reporting() === 0) return false;
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
},
E_WARNING
);
try {
$fp = fopen("http://example.com","r");
} catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Solution based on this thread/question.

Error Handling in simple_html_dom.php

I am a beginner in PHP and I have a similar problem to that handled in:
Good error handling with file_get_contents
In simple_html_dom.php, there is a function called load_file, which is:
function load_file() {
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
}
In my PHP script, I use this function as:
$html->load_file($link);
When I try to load a broken link, I get a warning message on my output display like:
Warning: file_get_contents(http://www.yurowdesigns.com/UkraineSIG/test.asp) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568
I would like to re-route this and similar error messages to an error.log file on my website rather than having it on my output display.
I naively tried to adapt the answer given in
Good error handling with file_get_contents
to my problem by adding the the function fget_contents() to my copy of simple_html_dom.php.
function fget_contents() {
$args = func_get_args();
// the # can be removed if you lower error_reporting level
$contents = #call_user_func_array('file_get_contents', $args);
if ($contents === false) {
throw new Exception('Failed to open ' . $file);
} else {
return $contents;
}
}
And changed line 568 in load_file to read:
$this->load(call_user_func_array('fget_contents', $args), true);
But now, when I run my PHP script, I get a new error message:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'fget_contents' not found or invalid function name in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568
Which means that simple_html_dom.php does not recognize the function 'fget_contents'
Where did I go wrong? How can I fix it?
Use the following code :
function load_file() {
try{
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
} catch(Exception e) {
print_r(e);
}
}
Here as you see it has try and catch block that will handle the errors.
To do that, in your PHP files, set them up to hide errors from being displayed. Use ini_set('display_errors','1'); and then log your errors using error_log or hopefully your default php.ini config already logs errors using the error_log string

Categories