PHP Error Handling - "missing argument for errorHandler" - php

I'm trying to setup error handling for the first time.
It does actually work and report errors if there is one, but for some reason it always shows errors of 'missing arguments' for the error handling function itself. Please note my error handling function is in a separate file and is included to the index page, I'm not sure if that's the problem :S
Here is my error handling function
function errorHandler($errno, $errstr, $error_file, $error_line) {
if(isset($errstr)) {
# There is an error, display it
echo $errno." - ".$errstr." in ".$error_file." at line ".$error_line."<br>";
} else {
# There isn't any error, do nothing
return false;
}
}
// We must tell PHP to use the above error handler.
set_error_handler("errorHanlder");
Here is the index page
<!-- # Error Handler -->
<? if(errorHandler()) { ?>
<section id="error-handler">
<?=errorHandler();?>
</section>
<? } ?>
Here is the result in the browser (bear in mind there is no php error, so this error handler shouldn't be outputting anything - this is what I can't understand
2 - Missing argument 1 for errorHandler(), called in index.php on line 20 and defined in inc/arcError.fnc.php at line 10
2 - Missing argument 2 for errorHandler(), called in index.php on line 20 and defined in inc/arcError.fnc.php at line 10
2 - Missing argument 3 for errorHandler(), called in index.php on line 20 and defined in inc/arcError.fnc.php at line 10
2 - Missing argument 4 for errorHandler(), called in index.php on line 20 and defined in inc/arcError.fnc.php at line 10
Any idea's why PHP is reporting the missing arguments?

You are calling the function with ZERO argument...
<?=errorHandler();?>
Why do you need to call it anyway?
And there are several typos in your code: replace "Hanlder" with "Handler".
There's no need to do that:
if(isset($errstr)) {
Your error-handling function is automatically called when there is an error (and ONLY in that case!). $errstr is a parameter of this function, it is always set when the function gets executed.
New code:
function errorHandler($errno, $errstr, $error_file, $error_line) {
# There is an error, display it
echo "<section id='error-handler'>$errno - $errstr in $error_file at line $error_line</section><br>";
}
// We must tell PHP to use the above error handler.
set_error_handler("errorHandler");

Related

PHP Static Function Called Twice

I'm building a MVC PHP framework. I'm working on error logging. I'm testing a system to show and log (in a .txt file) errors thrown by a try, catch block. Since it's short, I've included the whole of index.php:
<?php
// *** SETUP THE DOCUMENT ***
// Declare strict_types.
declare(strict_types = 1);
// Include the autoload file.
require_once "classes/autoload.php";
// Create a new config variable to allow us to call the config file from anywhere.
new Config();
// Setup error reporting according to the config.
error_reporting(Config::$config['defaults']['errReporting']);
ini_set("display_errors", Config::$config['defaults']['ini_setErrors']);
// Errors::showCatch("Test");
try {
$test = new QueryExamples();
$test->getTexts();
} catch (Error $e) {
Errors::showCatch($e);
}
unset($test);
I've got an autoloader setup already. I'll include the code of that if anyone wants it. The next bit is a file called errors.php which is called by the try, catch and, depending on how the configuration file for the framework is setup, shows the message on the screen and/or sends it to a log file:
class Errors{
static function showCatch($errMessage){
// If manual errors are turned on in the config file.
if(Config::$config['defaults']['manErrors'] == 1){
// Show the error message.
echo "<br />{$errMessage}<br />";
}
// Log the error.
Logs::logManError($errMessage);
die();
}
}
How and where it is logged in the file is handled by another static function in another document:
class Logs{
static function logManError($errMessage) {
// If custom error logging is turned on in the config file:
if (Config::$config['defaults']['customErrorsLogging'] == 1) {
// Get the file path from the config file.
$manErrors_file = Config::$config['paths']['customErrors'];
// Format the error message.
$logTxt = "New Custom Error - [".date("d/m/Y - H:i:s")."]\n".$errMessage."\n\n";
file_put_contents($manErrors_file, $logTxt, FILE_APPEND);
}
}
}
The output in the log file:
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
I changed the error message to try and find where the errors were being called:
// Format the error message.
// $logTxt = "New Custom Error - [".date("d/m/Y - H:i:s")."]\n".$errMessage."\n\n";
$logTxt = debug_backtrace()["0"]['file']." ".debug_backtrace()['0']['line']."\n".debug_backtrace()['1']['file']." ".debug_backtrace()['1']['line']."\n\n";
The output in the log file:
F:\xampp\htdocs\FRED 0.0.0\classes\errors.php 21
F:\xampp\htdocs\FRED 0.0.0\index.php 22
F:\xampp\htdocs\FRED 0.0.0\classes\errors.php 21
F:\xampp\htdocs\FRED 0.0.0\index.php 22
errors.php:21 is where I called the the Logs:logManError() static function and index.php:22 is where I called the Errors:showCatch() function in the try, catch block.
I also tried adding a global variable to index.php to check how many times the showCatch() function was being called:
(index.php)
$GLOBALS['i'] = 0;
(errors.php)
$GLOBALS['i'] += 1;
// Log the error.
Logs::logManError($errMessage."<br />".$GLOBALS['i']);
die();
The output:
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
1
New Custom Error - [23/03/2020 - 01:50:17]
Error: (Error message)
1
Okay. Here is the answer. After doing more research there appears to be nothing wrong with my code. It seems that it's something to do with the rewrite engine combined with a few other things. I've included a link to the page that gave me the solution.
https://www.sitepoint.com/community/t/duplicate-entries-with-file-put-contents-when-rewriteengine-on/16188/11

Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17

I'm not new to php but I'm unfamiliar with exceptions and OOP.
The problem here is that sometimes mysql doesn't load or loads after the web server. So I'm getting this fatal error:
PHP message: PHP Stack trace:
PHP message: PHP 1. {main}() /public_html/jpa.php:0
PHP message: PHP 2. require_once() /public_html/jpa.php:9
PHP message: PHP 3. require_once() /public_html/common/japan.php:9
PHP message: PHP 4. PDO->__construct('mysql:host=localhost;dbname=xxx;charset=utf8', 'xxx', 'xxx') /public_html/Connections/pdo.php:10
PHP message: PHP Fatal error: Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17
Here is my code, copied directly from the PHP page.
<?php
try
{
$db = new PDO("mysql:host={$hostname_data_connect};dbname={$database_data_connect};charset=utf8", "{$username_data_connect}", "{$password_data_connect}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $Exception )
{
// Note The Typecast To An Integer!
throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}
What I would like to achieve is to return a 503 maintenance message or redirect the user to a custom 503 maintenance message page instead of throwing a fatal exception. The time mysql finishes loading.
I have no idea how to do that. Please help.
Or perform a php check to test whether mysqld is up and running before executing the code above. Again I have no idea how to do that.
A snippet of code would be greatly appreciated. Dealing with that error for 3 years now.
MyDatabaseException is not a pre-defined PHP class, it's just an example name of something that you might create yourself, like $myString or myFunction(). But you haven't created any such class. Instead of just re-throwing the exception, perform your desired action in the catch block:
try {
// some db stuff
} catch PDOException($e) {
// maybe dynamically generate a 503 page
header('HTTP/1.1 503 Service Unavailable');
// output page content here
exit();
// or redirect to an existing one
header('Location: http://your.domain/your/503/page');
exit;
}

Extending the default php errors and error_log

I was wondering if anybody knows of a way to alter the default way an error message gets logged in PHP. Hopefully this can be applied to ALL messages, fatal errors, warnings, etc. as well as any time my script calls upon the error_log.
Currently the default error messages show up in the log as
[19-Feb-2017 15:38:42 America/Vancouver] Could not post employee data - no rows submitted
[20-Feb-2017 11:12:34 America/Toronto] PHP Warning: array_splice() expects parameter ...
But what would be greatly beneficial to me is if I could have it also include some variables that i have stored in $_SESSION for each user, such as the user's login and company. So for example the error could be output like the following
[19-Feb-2017 15:38:42 America/Vancouver] [CompanyXYZ/bob_smith] Could not post employee data - no rows submitted
[20-Feb-2017 11:12:34 America/Toronto] [OtherCompany/jimbo_redneck] PHP Warning: array_splice() expects parameter ...
Does anything like this exist in the world of PHP?
You can create your own error handling routine. You should be able to add whatever data you want to the error message. Something like this should get your started:
<?php
function my_handler($errno , $errstr, $errfile, $errline, $errcontext)
{
$msg = "Hey I got an error of type $errno ($errstr) from $errfile line $errline!";
$msg .= "Here's some more info: $_SESSION[foo]";
error_log($msg);
return true;
}
set_error_handler("my_handler");
Fatal errors are only caused by code problems such as syntax errors. They will not happen to users, so you don't need to worry about catching them.
Note that things change considerably in PHP 7.

PHP include call throws warnings but continues

I've got a pretty simple PHP script, but I can't for the life of me work out why one line doesn't work.
The main script:
<?php
include("/includes/processes.php");
?>
[...]
<?php
if(getUserLevel() == 3) {
?>
[...]
processes.php is in the right place and all that. It should be defining getUserLevel(). Here it is:
<?php
function getUserLevel() {
if(isset($_COOKIE["userlvl"]) && isset($_SESSION["userlvl"]) {
if($_COOKIE["userlvl"] == $_SESSION["userlvl"]) return $_SESSION["userlvl"];
else return 0;
}
else {
return 0;
}
}
function usernameIs($name) {
if($_COOKIE["username"] == $name && $_SESSION["username"] == $name) return true;
else return false;
}
?>
So when I go to index.php (the main script), it gives me two warnings and one fatal error:
Warning: include(/includes/processes.php): failed to open stream: No such file or directory in /home/u164546666/public_html/index.php on line 2
Warning: include(): Failed opening '/includes/processes.php' for inclusion (include_path='.:/opt/php-5.5/pear') in /home/u164546666/public_html/index.php on line 2
Fatal error: Call to undefined function getUserLevel() in /home/u164546666/public_html/index.php on line 27
(line 2 is the include() call, line 27 the call to getUserLevel())
It's pretty obvious why I've got the fatal error - because the include() has failed - but why is that? Is it a server config issue or have I just written it wrong?
The file tree:
index.php
/includes
/processes.php
You are probably need the relative path and is missing the .
<?php
include("./includes/processes.php");
?>
Change your include to
include_once dirname(__FILE__) . "/includes/processes.php";
However, I'd go for require as the file includes vital functionality.
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.
The issue is with your include statement. Just get rid of the parenthesis around that as:
include "/includes/processes.php";

How do I define fire_event, undefined fire_event error

I'm cleaning up all the errors in an old script and I'm getting one that says undefined function fire_event. How do I define fire_event. everything works fine but i've turned on error_reporting(E_ALL); to fix all hidden errors
Fatal error: Call to undefined function fire_event() in /home/social/public_html/includes/dologin.php on line 96
if (strpos($en['redirect'],'index.php?req=login')) unset($en['redirect']);
$redirect = (isset($en['redirect']) && $en['redirect']!='' ? $en['redirect'] : constant('dir').'members.html');
fire_event('member_login',$line['m_id']);
header('Location: '.$redirect);
exit;
}
That has to be some custom function and we don't know what belongs in there. Search all source files, because you most likely removed or changed a dependency and/or include() or required() line.

Categories