When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:
error_reporting(E_ERROR);
Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.
So you should first set it as verbose as possible with:
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
UPDATE: how to log errors instead of displaying them
As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.
A possible implementation is via the .htaccess file, useful if you don’t have access to the php.ini file (source).
# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
# Enable PHP error logging
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Prevent access to PHP error log
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
Несмотря на то, что error_reporting установлен в 0, ошибки базы данных все еще печатаются на экране. Есть ли параметр, который я могу изменить, чтобы отключить отчет об ошибках базы данных? Это для CodeIgniter v1.6.x
EDIT : Re: Ошибки исправления – Эм, да. Я хочу исправить ошибки. Я получаю уведомления об ошибках из своего журнала ошибок, а не из того, что мои посетители видят на экране. Это никому не помогает и вредит безопасности моей системы.
- Как реализовать Redis в CodeIgniter?
- Как изменить расширение в поле зрения с помощью codeigniter 3?
- Несколько видов просмотра Codeigniter в одном представлении
- Ошибка Codeigniter «Запрос URL не найден»
- создание обратных ссылок на страницы в Codeigniter
EDIT 2 : Установка error_reporting в 0 не влияет на встроенный класс регистрации ошибок CodeIgniter, начиная с записи в журнал ошибок.
- Codeigniter — как удалить index.php из url?
- CodeIgniter — Как скрыть index.php из URL-адреса
- Форма CodeIgniter всегда отправляет данные «0»
- PHP CodeIgniter: файл не загружается достаточно быстро, и он продолжает процесс без файла
- Как загрузить изображение на CodeIgniter и отобразить его на другой странице
Нашел ответ:
В config/database.php:
// ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
так:
$db['default']['db_debug'] = FALSE;
… должен быть отключен.
В дополнение к ответу Яна, чтобы временно отключить сообщения об ошибках:
$db_debug = $this->db->db_debug; $this->db->db_debug = false; // Do your sketchy stuff here $this->db->db_debug = $db_debug;
-
Вы не хотите изменять error_reporting на 0, поскольку это также подавляет ошибки при регистрации.
-
вместо этого вы должны изменить display_errors на 0
Это не объясняет, почему вы получаете ошибки, хотя, предполагая, что error_reporting на самом деле 0. Может быть, структура обрабатывает эти ошибки
Вы можете отредактировать файл /errors/db_error.php в каталоге приложения – это шаблон, включенный для ошибок БД.
Однако вы должны просто исправить ошибки.
Recommended Answers
Just use @ operator in the possible area of occuring the MySql errors in php code. This will hides the MySql errors to display…
Jump to Post
That’s ok… Just check your ftp username and password if you are working in remote server or mysql username and password if you are working in localhost…
Jump to Post
All 6 Replies
![]()
12 Years Ago
Just use @ operator in the possible area of occuring the MySql errors in php code. This will hides the MySql errors to display…
![]()
12 Years Ago
Yes I have used the suppression operator but this isn’t ideal. The user will still get an error message in some circumstances.
E.g, this code:
@ $dbconnect = mysql_connect("ipaddress", "username", "");
mysql_select_db("db");
This still displays the error:
Access denied for user 'user'@'domain' (using password: NO)
I want the errors to be logged, and NOT displayed to stdout at all!
Surely there’s a way to do this…?
Edited
12 Years Ago
by nonshatter because:
n/a
![]()
12 Years Ago
Never mind, I’ve created my own error handling function for mysql errors. Instead of suppressing the error messages (which isn’t particularly useful in a lot of situations), I’ve used a file handle to write these errors to my own log file:
This means users don’t get hold of info they shouldn’t. And this way I’ll be made aware of the errors instead of them being silenced by using ‘@’
E.g:
mysql_select_db("db") or (writeErrors(mysql_error(),$ip,$date,__FILE__,__LINE__));
function writeErrors($error,$ip,$date,$file,$line)
{
//write to the logfile
}
![]()
12 Years Ago
That’s ok… Just check your ftp username and password if you are working in remote server or mysql username and password if you are working in localhost…

12 Years Ago
I have turned off all the necessary options in php.ini such as
display_errors = Off
log_errors = On
error_log = /path/to/log/
I have even tried to override these settings using ini_set() in my script.
This prevents PHP syntax errors from being displayed, but Mysql errors are still being shown to the user!
How do I turn this off?…
![]()
12 Years Ago
Is there an «or die()» statement in your database handler?
Also, never use inline error suppression. Its not very good performance wise.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Recommended Answers
Just use @ operator in the possible area of occuring the MySql errors in php code. This will hides the MySql errors to display…
Jump to Post
That’s ok… Just check your ftp username and password if you are working in remote server or mysql username and password if you are working in localhost…
Jump to Post
All 6 Replies
![]()
12 Years Ago
Just use @ operator in the possible area of occuring the MySql errors in php code. This will hides the MySql errors to display…
![]()
12 Years Ago
Yes I have used the suppression operator but this isn’t ideal. The user will still get an error message in some circumstances.
E.g, this code:
@ $dbconnect = mysql_connect("ipaddress", "username", "");
mysql_select_db("db");
This still displays the error:
Access denied for user 'user'@'domain' (using password: NO)
I want the errors to be logged, and NOT displayed to stdout at all!
Surely there’s a way to do this…?
Edited
12 Years Ago
by nonshatter because:
n/a
![]()
12 Years Ago
Never mind, I’ve created my own error handling function for mysql errors. Instead of suppressing the error messages (which isn’t particularly useful in a lot of situations), I’ve used a file handle to write these errors to my own log file:
This means users don’t get hold of info they shouldn’t. And this way I’ll be made aware of the errors instead of them being silenced by using ‘@’
E.g:
mysql_select_db("db") or (writeErrors(mysql_error(),$ip,$date,__FILE__,__LINE__));
function writeErrors($error,$ip,$date,$file,$line)
{
//write to the logfile
}
![]()
12 Years Ago
That’s ok… Just check your ftp username and password if you are working in remote server or mysql username and password if you are working in localhost…

12 Years Ago
I have turned off all the necessary options in php.ini such as
display_errors = Off
log_errors = On
error_log = /path/to/log/
I have even tried to override these settings using ini_set() in my script.
This prevents PHP syntax errors from being displayed, but Mysql errors are still being shown to the user!
How do I turn this off?…
![]()
12 Years Ago
Is there an «or die()» statement in your database handler?
Also, never use inline error suppression. Its not very good performance wise.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Есть ли способ предотвратить появление ошибок MySql (если они возникли) на клиенте, и просто их где-то регистрировать?
Примечание 1:
Я не использую никаких фреймворков, просто нативный PHP с PDO Extinsion и MySql.
Заметка 2:
Этот код остановит ошибки PHP, а не MySql.
ini_set('display_errors', 0);
ini_set("display_startup_errors", 0);
error_reporting(0);
Пример:
отключение ошибок, таких как
SQLSTATE[HY000] [1045] Access denied for user ..
0
Решение
Для ошибок, не связанных с PHP, приложение (программист) отвечает за получение и отображение / запись ошибки. Так что для вашего конкретного примера не отображайте его, зарегистрируйте его:
//instead of displaying
if (!$link) {
die(mysqli_connect_error());
}
//log it
if (!$link) {
error_log(mysqli_connect_error());
}
Вы могли бы также нас trigger_error это будет соответствовать вашим настройкам сообщения об ошибках:
if (!$link) {
trigger_error(mysqli_connect_error(), E_USER_ERROR);
}
1
Другие решения
Других решений пока нет …
|
Nishen 1172 / 833 / 359 Регистрация: 26.02.2015 Сообщений: 3,743 |
||||
|
1 |
||||
|
20.02.2016, 17:08. Показов 719. Ответов 4 Метки нет (Все метки)
Всех приветствую!
, но поторопился и не верно указал логин для авторизации. Можно ли сделать так, чтобы не возвращалось от сервера что-то вроде: Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root1’@’localhost’ (using password: NO) in Просто я к серверу обращаюсь с помощью AJAX и хочу возвращать коды и текст ошибок с помощью JSON. Добавлено через 30 секунд
0 |
|
4833 / 3848 / 1596 Регистрация: 24.04.2014 Сообщений: 11,292 |
|
|
20.02.2016, 17:15 |
2 |
|
Для начала воспользоваться современным расширением для работы с бд: mysqli или PDO.
Чтобы описание ошибок было более читабельным для обычного пользователя. Пользователю вообще не надо знать что не удалось к бд подключиться. Вернуть код 500 и сообщение типа: произошла ошибка, повторите попытку позже.
0 |
|
Nishen 1172 / 833 / 359 Регистрация: 26.02.2015 Сообщений: 3,743 |
||||
|
20.02.2016, 17:31 [ТС] |
3 |
|||
|
Для начала воспользоваться современным расширением для работы с бд: mysqli или PDO. Спасибо, не знал. Я далек от WEB.
Пользователю вообще не надо знать что не удалось к бд подключиться. Не, не надо, но я и хотел вернуть сообщение вроде твоего.
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root1’@’localhost’ (using password: NO) in
Вернуть код 500 Подскажешь, как это сделать можно? Нашел, что можно отключать вывод ошибок таким способом
Насколько это правильно?
0 |
|
Jewbacabra
4833 / 3848 / 1596 Регистрация: 24.04.2014 Сообщений: 11,292 |
||||
|
20.02.2016, 17:50 |
4 |
|||
|
Но php постоянно вставляет «палки в колеса» и пихает на страницу Это не php, это косяк расширения mysql. Ситуация когда не удалось подключиться к бд — не является само по себе ошибкой, оно может быть определенным способом обработана, и следовательно кидать в данном случае варнинг, … ну я не знаю о чем разработчики думали, когда такое сделали. Эта одна из причин, почему лучше перейти на другие расширения работы с бд.
Подскажешь, как это сделать можно?
Нашел, что можно отключать вывод ошибок таким способом Для готового приложения, когда оно уже функционирует нормально.
1 |
|
1172 / 833 / 359 Регистрация: 26.02.2015 Сообщений: 3,743 |
|
|
20.02.2016, 18:05 [ТС] |
5 |
|
Jewbacabra, спасибо тебе огромное! Ты мне помог.
0 |
(PHP 4, PHP 5, PHP 7, PHP 8)
error_reporting — Sets which PHP errors are reported
Description
error_reporting(?int $error_level = null): int
Parameters
-
error_level -
The new error_reporting
level. It takes on either a bitmask, or named constants. Using named
constants is strongly encouraged to ensure compatibility for future
versions. As error levels are added, the range of integers increases,
so older integer-based error levels will not always behave as expected.The available error level constants and the actual
meanings of these error levels are described in the
predefined constants.
Return Values
Returns the old error_reporting
level or the current level if no error_level parameter is
given.
Changelog
| Version | Description |
|---|---|
| 8.0.0 |
error_level is nullable now.
|
Examples
Example #1 error_reporting() examples
<?php// Turn off all error reporting
error_reporting(0);// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);// Report all PHP errors
error_reporting(E_ALL);// Report all PHP errors
error_reporting(-1);// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>
Notes
Tip
Passing in the value -1 will show every possible error,
even when new levels and constants are added in future PHP versions. The
behavior is equivalent to passing E_ALL constant.
See Also
- The display_errors directive
- The html_errors directive
- The xmlrpc_errors directive
- ini_set() — Sets the value of a configuration option
info at hephoz dot de ¶
14 years ago
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:
- create a new file in which you include the faulty script:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
- execute this file instead of the faulty script file
now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
jcastromail at yahoo dot es ¶
2 years ago
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.
For example
<?php
$a
=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8?>
dave at davidhbrown dot us ¶
16 years ago
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.
If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:
<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>
^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
Fernando Piancastelli ¶
18 years ago
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set
display_errors = On
error_reporting = ~E_ALL
to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
lhenry at lhenry dot com ¶
3 years ago
In php7, what was generally a notice or a deprecated is now a warning : the same level of a mysql error … unacceptable for me.
I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.
So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING
Custom overriding the level of php errors should be super handy and flexible …
luisdev ¶
4 years ago
This article refers to these two reporting levels:
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
What is the difference between those two levels?
Please update this article with a clear explanation of the difference and the possible use cases.
ecervetti at orupaca dot fr ¶
13 years ago
It could save two minutes to someone:
E_ALL & ~E_NOTICE integer value is 6135
qeremy ! gmail ¶
7 years ago
If you want to see all errors in your local environment, you can set your project URL like "foo.com.local" locally and put that in bootstrap file.
<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
// or error_reporting(E_ALL);
}
?>
Rash ¶
8 years ago
If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.
So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.
chris at ocproducts dot com ¶
6 years ago
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
keithm at aoeex dot com ¶
12 years ago
Some E_STRICT errors seem to be thrown during the page's compilation process. This means they cannot be disabled by dynamically altering the error level at run time within that page.
The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.
Ex, rename index.php to index.inc.php, then re-create index.php as:
<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>
That allows you to alter the error reporting prior to the file being compiled.
I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
huhiko334 at yandex dot ru ¶
4 years ago
If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct
kevinson112 at yahoo dot com ¶
4 years ago
I had the problem that if there was an error, php would just give me a blank page. Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc. But simply running the file in a different directory allowed it to show errors!
Turns out that the error_log file in the one directory was full (2.0 Gb). I erased the file and now errors are displayed normally. It might also help to turn error logging off.
https://techysupport.co/norton-tech-support/
adam at adamhahn dot com ¶
5 years ago
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.
<?php
error_reporting(E_ALL);
var_dump(
error_reporting(), // value of E_ALL,
@error_reporting() // value is 0
);
?>
kc8yds at gmail dot com ¶
14 years ago
this is to show all errors for code that may be run on different versions
for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL
if anyone sees any problems with it please correct this post
<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
vdephily at bluemetrix dot com ¶
17 years ago
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);$foo = $bar; //notice : $bar uninitialized$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok$foo = $bar['nope'] // notice : no such index
?>
fredrik at demomusic dot nu ¶
17 years ago
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".
This is very useful to remember when setting error_reporting levels in httpd.conf:
Use the table above or:
<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>
To get the appropriate integer for your error-level. Then use:
php_admin_value error_reporting YOUR_INT
in httpd.conf
I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...
Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
rojaro at gmail dot com ¶
12 years ago
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:
<?php error_reporting(-1); ?>
j dot schriver at vindiou dot com ¶
22 years ago
error_reporting() has no effect if you have defined your own error handler with set_error_handler()
[Editor's Note: This is not quite accurate.
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.
All other levels of errors will be passed to the custom error handler defined by set_error_handler().
Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:
if (!($type & error_reporting())) return;
-zak@php.net]
teynon1 at gmail dot com ¶
10 years ago
It might be a good idea to include E_COMPILE_ERROR in error_reporting.
If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.
Example:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function
myErrorHandler($errno, $errstr, $errfile, $errline) {
// Do something other than output message.
return true;
}$old_error_handler = set_error_handler("myErrorHandler");
require
"this file does not exist";
?>
To prevent this, simply include E_COMPILE_ERROR in the error_reporting.
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
misplacedme at gmail dot com ¶
13 years ago
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>
I made this function to make things a little bit quicker. Unset values passed by reference won't trigger a notice.
<?php
function test_ref(&$var,$test_function='',$negate=false) {
$stat = true;
if(!isset($var)) $stat = false;
if (!empty($test_function) && function_exists($test_function)){
$stat = $test_function($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif($test_function == 'empty') {
$stat = empty($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif (!function_exists($test_function)) {
$stat = false;
trigger_error("$test_function() is not a valid function");
}
$stat = ($stat) ? true : false;
return $stat;
}
$a = '';
$b = '15';test_ref($a,'empty',true); //False
test_ref($a,'is_int'); //False
test_ref($a,'is_numeric'); //False
test_ref($b,'empty',true); //true
test_ref($b,'is_int'); //False
test_ref($b,'is_numeric'); //false
test_ref($unset,'is_numeric'); //false
test_ref($b,'is_number'); //returns false, with an error.
?>
Alex ¶
16 years ago
error_reporting() may give unexpected results if the @ error suppression directive is used.
<?php
@include 'config.php';
include 'foo.bar'; // non-existent file
?>
config.php
<?php
error_reporting(0);
?>
will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings). If the suppressor is removed, this works as expected.
Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result. This is contrary to the note above which says that the two instructions are equivalent.
Daz Williams (The Northeast) ¶
13 years ago
Only display php errors to the developer...
<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
ini_set('display_errors','On');
}
else
{
ini_set('display_errors','Off');
}
?>
Just replace 00.00.00.00 with your ip address.
forcemdt ¶
9 years ago
Php >5.4
Creating a Custom Error Handler
set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
DarkGool ¶
17 years ago
In phpinfo() error reporting level display like a bit (such as 4095)
Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file
<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
$end = $i;
}
$res[] = $end;
$bit = $bit - $end;
}
?>
In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8) // E_NOTICE
...
&IT ¶
2 years ago
error_reporting(E_ALL);
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}

