Error Handling in simple_html_dom.php - 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

Related

php make set_error_handler return an error string

I need to put a contents of 'PHP Warning' into a variable. For these purposes I got the following code (set_error_handler() in a php class):
$data = '';
set_error_handler( function() use ($this, &$data) { $data = $this->my_error_handler(); return $data; } );
//some code that throws Warning
restore_error_handler();
function my_error_handler($errno, $errstr) {
return $errstr;
}
But I get the following 500 error: Type error: Too few arguments to function my_error_handler(), 0 passed.
If I replace a callable above with a string, code works without a 500 error, but I cannot pass a variable in it and return it with a contents of warning thrown. Any ideas how to fix it? Thank you.

File_get_contents not evaluating to false when file does not exist

I'm trying to test an exception in my code.
public function testGetFileThrowsException(){
$this->expectException(FileNotFoundException::class);
$file = "db.json";
$this->review->getData($file);
}
The "db.json" file doesn't exist. My goal is tp have the getData() file to throw the FileNotFoundException. Here is the getData() code:
public function getData($path){
if(file_get_contents($path) === false){
throw new FileNotFoundException;
}
return $file;
}
The problem is that instead of evaluating to False and throw the exception, the file_get_contents function returns:
1) CompanyReviewTest::testGetFileThrowsException
file_get_contents(db.json): failed to open stream: No such file or directory
So the test doesn't run successfully. Any ideas on why does this happen?
file_get_contents() generates an E_WARNING level error (failed to open stream) which is what you'll want to suppress as you're already handling it with your exception class.
You can suppress this warning by adding PHP's error control operator # in front of file_get_contents(), example:
<?php
$path = 'test.php';
if (#file_get_contents($path) === false) {
echo 'false';
die();
}
echo 'true';
?>
The above echoes false, without the # operator it returns both the E_WARNING and the echoed false. It may be the case that the warning error is interfering with your throw function, but without seeing the code for that it's hard to say.
You have 2 solution the poor one is to hide the error like that
public function getData($path){
if(#file_get_contents($path) === false){
throw new FileNotFoundException;
}
return $file;
}
Or check maybe if the file exist (better solution i guess)
public function getData($path){
if(file_exists($path) === false){
throw new FileNotFoundException;
}
return $file;
}

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.

How to catch invalid image when using PHP imagecreatefromstring

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

fopen in XMLRPC need to return error not die

So I have a XMLRPC developed in Zend PHP and I'm trying to return the error message instead of using the die().
Here is what I have:
$this->fh = fopen($this->log_file, 'a')
or die("Can't open log file: ".$this->log_file);
Is something like this possible? (Pseudo code)
if($this->fh = fopen($this->log_file, 'a')) {
return "Can't open log file: ".$this->log_file;
}
It's probably right under my nose just having a brain fart I guess
Solution:
For the XMLRPC process the E_WARNING will kill/crash the process. To have the XMLRPC
respond with the warning message use the # symbol in front of the function to suppress
the warning. http://php.net/manual/en/function.fopen.php #Errors/Exceptions
// If the open fails,
// an error of level E_WARNING is generated.
// You may use # to suppress this warning.
if(!($this->fh = #fopen($this->log_file, 'a'))) {
return "Can't open log file: ".$this->log_file;
}
if(!($this->fh = fopen($this->log_file, 'a'))) {
return "Can't open log file: ".$this->log_file;
}
// if you get here, $this->fh contains a file handle
There's nothing wrong with using the return as you speculate, however you'll need to ensure that you handle this behaviour within the calling function.
To determine if the fopen was successful, you can either compare the return value inline as per your example or use the is_resource function on the file handle.
fopen return:
if($this->fh = fopen($this->log_file, 'a')) {
// Everything is fine.
}
else {
// Error condition...
return "Can't open log file: ".$this->log_file;
}
is_resource:
$this->fh = fopen($this->log_file, 'a');
if(is_resource($this->fh)) {
// Everything is fine...
}
else {
// Error condition...
return "Can't open log file: ".$this->log_file;
}

Categories