How would I write a MySQL error to a file instead of displaying it to the user?
here is what I have so far...
if (!mysql_query($sql_query,$connection))
{
die('Error: ' . mysql_error());
}
echo "Success!";
You can use the error_log function in php for that.
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
Edit: so in your case this would look like the following (although i would use a different if statement)
if (!mysql_query($sql_query,$connection))
{
error_log(mysql_error() . "\n", 3, "/var/tmp/my-errors.log");
}
echo "Success!";
Use error_log, or fopen/fwrite/fclose/etc.
I often use create my own error handler with something like set_error_handler in PHP and use trigger_error to capture ALL errors and write them to file. This may be a better scenario for you; rather than writing numerous error_log()'s, you can just create an error handler function and then use trigger_error.
Firstly, you should not use die if you do not want to display your error message to the user.
Secondly, instead of using die, you must log your error message into a file. If you are using some logging library, you may output the error to some log, else you may want to have a look at File handling in PHP.
Link - http://davidwalsh.name/basic-php-file-handling-create-open-read-write-append-close-delete
Related
I came across in a project of about 900 files with 3 millions lines of code, and my boss asked me to find a solution to prevent mysql_error() to show errors.
This is the syntax
mysql_query() OR die(mysql_error())
So, how can I disable the mysql_error() from showing errors?
function mysql_own_error($debug = false){
$msg = mysql_error();
if($debug){
echo $msg;
}else{
// Function to log errors here.
}
}
With that you can set a global debug-variable $debug. Only if that is true output the error msg.
Now replace every mysql_error() with mysql_own_error($debug). There are Editors that can do suche replaces fast.
With that you will prevent the mysql_error() from showing errors publicly but you can still debug the code if you need to.
If you're still having errors then your project is not finished yet.
One way would be to do a site-wide find/replace on your files and replace the OR die(mysql_error()) with an # in front of mysql_error() like so: OR die(#mysql_error()).
Placing an # in front of a function call suppresses error messages. But use it carefully, this is not always a good solution.
Read this post which links to this article to know if it's a good solution for you.
I would change all OR die() occourrences to a custom error-handling function, then if you get an error you will still know about it without displaying them to users.
Yes, it would take a lot of time, but a good project takes a lot of time.
Check this article to create your own error-handling function and this other one to Enable PHP error logging via .htaccess, they really helped me.
I've never worked with advanced error handling, and I can't find an obvious answer searching.
In the scope a script (require_once) how do you set up a custom "die" message?
Generally my users see the page-load die with no response. I'd like to direct them to a help file regarding memory so they absolutely cannot miss the solution.
You can kill a script and output a message using the die() command
die("Your message here");
You can also throw custom exceptions in PHP 5+, and catch them and at that point output a message to the users.
http://php.net/manual/en/language.exceptions.php
require_once automatically stops execution if it fails.
Try e.g. (include_once file.php) or header('Location: http://.../path/to/help');, or
if(!(include_once file.php)) {
// redirect?
}
What I want to do is when an if condition doesn't go as it should, instead of echo'ing the my custom error message in else { }, storing the error message somewhere else and retrieving it from another page.
For example, this is my page with the if condition:
if ($something < 4){
echo 'yes it is less than four';
else { echo 'no it isn\'t less than four';}
I want to for example store these error messages in strings and give them numbers:
if ($something < 4){
$debug11 = 'yes it is less than four';
echo '11';
else { $debug10 = 'no it isn\'t less than four'; echo '10'; }
then let's assume there's a debug.php file with php class that can echo these messages but in order to do so it needs to know what $debug11 is, can it do that without including that php page? is that what public strings are for? or should I just define all of them in debug.php
the point of all this is that jquery will call this file.php and get a message like 11 or 10 which in this case is success or failure then I will be able to know why it failed with debug.php. numbers are easier since I may play with text messages a lot and easier to confirm with numbers than text in if conditions.
You want to store error-messages and read this messages by another script.
It means you need a storage.
As a storage, you can use files, or memcache, or APC, or queues.
Create logger, which will write messages to the storage, and then in debug.php you will read list of messages from the storage.
I recommend to use Memcache, set_error_handler and trigger_error.
I'm not sure what you mean by 'public strings', but if you are looking at accessing a variable between 2 pages, you would need to persist them into a session variable at least.
Also you might be better off using PHP assertions to check for error conditions within your code (I think that's what your trying to achieve here):
Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.
Try logging to file: http://nl3.php.net/manual/en/errorfunc.configuration.php#ini.error-log. You can supply a custom log file in which you can find all your errors.
If you put in a error handler you should be able to create debug messages and store them in another file.
Write own logging mechanism and put log messages in a file.
As above I am not 100% sure what you are trying to do, however instead of using variables for your custom error messages it may be better to use Constants. The benefits of them are that the values can't be rewritten unlike your variable where you can change the value within your script.
Your code would look something like this:
define("ERROR1", "It wont Work!");
define("ERROR2", "It still wont Work!");
define("ERROR3", "It must be broken!");
if ($something < 4){
echo '11';
} else {
echo ERROR1; // Prints "It wont Work!"
}
You can store these Constants in your debug.php file and use them on any page you include the file on.
Hope this helps.
Common handler i used
<?php
function error_msg($err_type,$err_msg,$err_file,$err_line)
{
$fh=fopen("error/errorlog.txt","a");
$date1=date("Y-m-d H:i:s");
$er="
===============================================================================================================
"."
Error: Type: ".$err_type."Message: ".$err_msg."ErrorFile: ".$err_file."Errorline: ".$err_line."Time: ".$date1.
"
===============================================================================================================
";
fwrite($fh,$er);
fclose($fh);
}
set_error_handler("error_msg");
?>
These codes Log error perfectly. Since i am using framework i cant use this codes. so i am using KLogger. KLogger perfectly logs my error but it also display error in front screen to user.
How to log error using KLogger If any one use this KLogger Help me how to use with simple examples.
Just do something like:
require_once 'KLogger.php';
$log = KLogger::instance('/var/log/');
$log->logInfo('Returned a million search results');
$log->logFatal('Oh dear.');
# Output will log to the path you specified, at log_[current-date].txt
It's crazy simple. Read the docs at GitHub
PS, I wrote KLogger.
I am using PHP 4, the only way I know of to cause an error and stop everything is calling die(). But in case I run into the error later and don't remember where its coming from I would like to specify the page and line number that the die() occurred on (like other php errors do). Is there a way to do this?
Thanks!
You should look into the magic constants.
echo __LINE__; // Line number
You can also run error_log() to send errors quietly to the log.
I think you should use trigger_error() to generate an E_USER_ERROR or E_USER_WARNING. This allows you to control the behaviour in detail. For example you can specify whether the messages should be shown at all using error_reporting(), or handle the E_USER_WARNING:s explicitly using set_error_handler().
The simplest way is to use:
echo __FILE__ . ": line " . __LINE__;
die();
If you were to use PHP5, you could also use Exceptions:
throw new Exception("My error message!");
The stack trace will reveal the whole call stack and the line this was thrown on.
(EDIT: Thanks to [#John Isaacs] and [#Emil H] for informing me that Exceptions weren't added to PHP until PHP5)
In addition to #Jukka Dahlbom and #Ólafur Waage's suggestions you might also consider using debug_backtrace().
Better use error_log() to report an error and debug_backtrace() for debugging. You could also write your own error handling function (see set_error_handler()) to combine both.