Php отключить ошибки функции

I have some PHP code. When I run it, a warning message appears.

How can I remove/suppress/ignore these warning messages?

Banee Ishaque K's user avatar

asked Jan 1, 2010 at 0:32

Alireza's user avatar

1

You really should fix whatever’s causing the warning, but you can control visibility of errors with error_reporting(). To skip warning messages, you could use something like:

error_reporting(E_ERROR | E_PARSE);

Sean Bright's user avatar

Sean Bright

118k17 gold badges138 silver badges145 bronze badges

answered Jan 1, 2010 at 0:37

Tatu Ulmanen's user avatar

Tatu UlmanenTatu Ulmanen

123k34 gold badges186 silver badges184 bronze badges

4

You can put an @ in front of your function call to suppress all error messages.

@yourFunctionHere();

Mark Amery's user avatar

Mark Amery

141k78 gold badges402 silver badges457 bronze badges

answered Jan 1, 2010 at 0:41

PetPaulsen's user avatar

PetPaulsenPetPaulsen

3,3922 gold badges22 silver badges33 bronze badges

11

To suppress warnings while leaving all other error reporting enabled:

error_reporting(E_ALL ^ E_WARNING); 

Mark Amery's user avatar

Mark Amery

141k78 gold badges402 silver badges457 bronze badges

answered Feb 11, 2011 at 8:08

Karthik's user avatar

KarthikKarthik

1,4183 gold badges17 silver badges29 bronze badges

If you don’t want to show warnings as well as errors use

// Turn off all error reporting
error_reporting(0);

Error Reporting — PHP Manual

MD XF's user avatar

MD XF

7,8027 gold badges40 silver badges71 bronze badges

answered Jan 22, 2013 at 3:16

mohan.gade's user avatar

mohan.gademohan.gade

1,0951 gold badge9 silver badges15 bronze badges

0

If you want to suppress the warnings and some other error types (for example, notices) while displaying all other errors, you can do:

error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

answered Jan 10, 2018 at 17:13

zstate's user avatar

zstatezstate

1,9851 gold badge18 silver badges20 bronze badges

in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.

In WordPress hide Warnings and Notices add following code in wp-config.php file

ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

answered May 12, 2017 at 5:04

Vijay Lathiya's user avatar

1

I do it as follows in my php.ini:

error_reporting = E_ALL & ~E_WARNING  & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

This logs only fatal errors and no warnings.

honk's user avatar

honk

9,05711 gold badges74 silver badges83 bronze badges

answered Feb 27, 2018 at 8:43

navid's user avatar

navidnavid

9528 silver badges19 bronze badges

0

Not exactly answering the question, but I think this is a better compromise in some situations:

I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was — a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:

printf('<div style="display:none">');
    ...Third-party stuff here...
printf('</div>');

Warning was still in page source as a reminder to me, but invisible to the client.

FelixSFD's user avatar

FelixSFD

5,98210 gold badges43 silver badges115 bronze badges

answered Dec 30, 2012 at 20:03

DaveWalley's user avatar

DaveWalleyDaveWalley

80710 silver badges22 bronze badges

4

I think that better solution is configuration of .htaccess In that way you dont have to alter code of application. Here are directives for Apache2

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

answered May 10, 2014 at 16:34

Sebastian Piskorski's user avatar

You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges132 bronze badges

answered Jan 1, 2010 at 0:34

Pekka's user avatar

PekkaPekka

440k141 gold badges972 silver badges1085 bronze badges

1

There is already answer with Error Control Operator but it lacks of explanation. You can use @ operator with every expression and it hides errors (except of Fatal Errors).

@$test['test']; //PHP Notice:  Undefined variable: test

@(14/0); // PHP Warning:  Division by zero

//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error:  Uncaught Error: Call to undefined function customFuntion()

For debugging it’s fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.

You should consider instead:

1. Error reporting settings as mentioned in accepted answer.

error_reporting(E_ERROR | E_PARSE);

or from PHP INI settings

ini_set('display_errors','Off');

2. Catching exceptions

try {
    $var->method();
} catch (Error $e) {
    // Handle error
    echo $e->getMessage();
}

answered May 24, 2020 at 3:28

Jsowa's user avatar

JsowaJsowa

8,7945 gold badges53 silver badges60 bronze badges

Оператор управления ошибками

PHP поддерживает один оператор управления ошибками: знак @.
В случае, если он предшествует какому-либо выражению в PHP-коде, любые
сообщения об ошибках, генерируемые этим выражением, будут подавлены.

Если пользовательская функция обработчика ошибок установлена с помощью
set_error_handler(), она всё равно будет вызываться,
даже если диагностика была подавлена.

Внимание

До версии PHP 8.0.0 функция error_reporting(), вызываемая внутри пользовательского обработчика ошибок,
всегда возвращала 0, если ошибка была подавлена оператором @.
Начиная с PHP 8.0.0, она возвращает значение E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE.

Любое сообщение об ошибке, сгенерированное выражением, доступно
в элементе массива "message", возвращаемого error_get_last().
Результат этой функции будет меняться при каждой ошибке, поэтому его необходимо проверить заранее.


<?php
// Преднамеренная ошибка при работе с файлами
$my_file = @file ('non_existent_file') or
die (
"Ошибка при открытии файла: сообщение об ошибке было таким: '" . error_get_last()['message'] . "'");// работает для любых выражений, а не только для функций
$value = @$cache[$key];
// В случае если ключа $key нет, сообщение об ошибке (notice) не будет отображено?>

Замечание:

Оператор @ работает только с
выражениями.
Есть простое правило: если что-то возвращает
значение, значит вы можете использовать перед ним оператор
@. Например, вы можете использовать @ перед
именем переменной, произвольной функцией или вызовом include и так далее. В то же время вы не можете использовать этот оператор
перед определением функции или класса, условными конструкциями, такими как if,
foreach и т.д.

Внимание

До PHP 8.0.0 оператор @ мог подавлять критические ошибки, которые прерывали выполнение скрипта.
Например, добавление @ к вызову несуществующей функции,
в случае, если она недоступна или написана неправильно, дальнейшая
работа скрипта приведёт к прерыванию выполнения скрипта без каких-либо уведомлений.

taras dot dot dot di at gmail dot com

14 years ago


I was confused as to what the @ symbol actually does, and after a few experiments have concluded the following:

* the error handler that is set gets called regardless of what level the error reporting is set on, or whether the statement is preceeded with @

* it is up to the error handler to impart some meaning on the different error levels. You could make your custom error handler echo all errors, even if error reporting is set to NONE.

* so what does the @ operator do? It temporarily sets the error reporting level to 0 for that line. If that line triggers an error, the error handler will still be called, but it will be called with an error level of 0

Hope this helps someone


M. T.

13 years ago


Be aware of using error control operator in statements before include() like this:

<?PHP(@include("file.php"))
OR die(
"Could not find file.php!");?>

This cause, that error reporting level is set to zero also for the included file. So if there are some errors in the included file, they will be not displayed.


Anonymous

9 years ago


This operator is affectionately known by veteran phpers as the stfu operator.

anthon at piwik dot org

12 years ago


If you're wondering what the performance impact of using the @ operator is, consider this example.  Here, the second script (using the @ operator) takes 1.75x as long to execute...almost double the time of the first script.

So while yes, there is some overhead, per iteration, we see that the @ operator added only .005 ms per call.  Not reason enough, imho, to avoid using the @ operator.

<?php

function x() { }

for (
$i = 0; $i < 1000000; $i++) { x(); }

?>



real    0m7.617s

user    0m6.788s

sys    0m0.792s

vs

<?php

function x() { }

for (
$i = 0; $i < 1000000; $i++) { @x(); }

?>



real    0m13.333s

user    0m12.437s

sys    0m0.836s


gerrywastaken

14 years ago


Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

It is far better to test for the condition that you know will cause an error before preceding to run the code. This way only the error that you know about will be suppressed and not all future errors associated with that piece of code.

There may be a good reason for using outright error suppression in favor of the method I have suggested, however in the many years I've spent programming web apps I've yet to come across a situation where it was a good solution. The examples given on this manual page are certainly not situations where the error control operator should be used.


jcmargentina at gmail dot com

3 years ago


Please be aware that the behaviour of this operator changed from php5 to php7.

The following code will raise a Fatal error no matter what, and you wont be able to suppress it

<?phpfunction query()
{
   
$myrs = null;
   
$tmp = @$myrs->free_result();

    return

$tmp;
}
var_dump(query());

echo

"THIS IS NOT PRINT";
?>

more info at: https://bugs.php.net/bug.php?id=78532&thanks=3


dkellner

6 years ago


There is no reason to NOT use something just because "it can be misused".  You could as well say "unlink is evil, you can delete files with it so don't ever use unlink".

It's a valid point that the @ operator hides all errors - so my rule of thumb is: use it only if you're aware of all possible errors your expression can throw AND you consider all of them irrelevant.

A simple example is
<?php

    $x

= @$a["name"];?>
There are only 2 possible problems here: a missing variable or a missing index.  If you're sure you're fine with both cases, you're good to go.  And again: suppressing errors is not a crime.  Not knowing when it's safe to suppress them is definitely worse.


man13or at hotmail dot fr

3 years ago


Quick debugging methods :

@print($a);
is equivalent to
if isset($a) echo $a ;

@a++;
is equivalent to
if isset($a) $a++ ;
else $a = 1;


Ryan C

2 years ago


It's still possible to detect when the @ operator is being used in the error handler in PHP8. Calling error_reporting() will no longer return 0 as documented, but using the @ operator does still change the return value when you call error_reporting().

My PHP error settings are set to use E_ALL, and when I call error_reporting() from the error handler of a non-suppressed error, it returns E_ALL as expected.

But when an error occurs on an expression where I tried to suppress the error with the @ operator, it returns: E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR (or the number 4437).

I didn't want to use 4437 in my code in case it changes with different settings or future versions of PHP, so I now use:

<?php
  
function my_error_handler($err_no, $err_msg, $filename, $linenum) {
      if (
error_reporting() != E_ALL) {
         return
false; // Silenced
     
}// ...
  
}
?>

If the code needs to work with all versions of PHP, you could check that error_reporting() doesn't equal E_ALL or 0.

And, of course, if your error_reporting settings in PHP is something other than E_ALL, you'll have to change that to whatever setting you do use.


darren at powerssa dot com

12 years ago


After some time investigating as to why I was still getting errors that were supposed to be suppressed with @ I found the following.

1. If you have set your own default error handler then the error still gets sent to the error handler regardless of the @ sign.

2. As mentioned below the @ suppression only changes the error level for that call. This is not to say that in your error handler you can check the given $errno for a value of 0 as the $errno will still refer to the TYPE(not the error level) of error e.g. E_WARNING or E_ERROR etc

3. The @ only changes the rumtime error reporting level just for that one call to 0. This means inside your custom error handler you can check the current runtime error_reporting level using error_reporting() (note that one must NOT pass any parameter to this function if you want to get the current value) and if its zero then you know that it has been suppressed.
<?php
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (
0 == error_reporting () ) {
       
// Error reporting is currently turned off or suppressed with @
       
return;
    }
   
// Do your normal custom error reporting here
}
?>

For more info on setting a custom error handler see: http://php.net/manual/en/function.set-error-handler.php
For more info on error_reporting see: http://www.php.net/manual/en/function.error-reporting.php


auser at anexample dot com

12 years ago


Be aware that using @ is dog-slow, as PHP incurs overhead to suppressing errors in this way. It's a trade-off between speed and convenience.

bohwaz

11 years ago


If you use the ErrorException exception to have a unified error management, I'll advise you to test against error_reporting in the error handler, not in the exception handler as you might encounter some headaches like blank pages as error_reporting might not be transmitted to exception handler.

So instead of :

<?phpfunction exception_error_handler($errno, $errstr, $errfile, $errline )
{
    throw new
ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

function

catchException($e)
{
    if (
error_reporting() === 0)
    {
        return;
    }
// Do some stuff
}set_exception_handler('catchException');?>

It would be better to do :

<?phpfunction exception_error_handler($errno, $errstr, $errfile, $errline )
{
    if (
error_reporting() === 0)
    {
        return;
    }

    throw new

ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

function

catchException($e)
{
   
// Do some stuff
}set_exception_handler('catchException');?>


programming at kennebel dot com

16 years ago


To suppress errors for a new class/object:

<?php
// Tested: PHP 5.1.2 ~ 2006-10-13

// Typical Example

$var = @some_function();// Class/Object Example
$var = @new some_class();// Does NOT Work!
//$var = new @some_class(); // syntax error
?>

I found this most useful when connecting to a
database, where i wanted to control the errors
and warnings displayed to the client, while still
using the class style of access.


frogger at netsurf dot de

18 years ago


Better use the function trigger_error() (http://de.php.net/manual/en/function.trigger-error.php)
to display defined notices, warnings and errors than check the error level your self. this lets you write messages to logfiles if defined in the php.ini, output
messages in dependency to the error_reporting() level and suppress output using the @-sign.

karst dot REMOVETHIS at onlinq dot nl

8 years ago


While you should definitely not be too liberal with the @ operator, I also disagree with people who claim it's the ultimate sin.

For example, a very reasonable use is to suppress the notice-level error generated by parse_ini_file() if you know the .ini file may be missing.
In my case getting the FALSE return value was enough to handle that situation, but I didn't want notice errors being output by my API.

TL;DR: Use it, but only if you know what you're suppressing and why.


ricovox

6 years ago


What is PHP's behavior for a variable that is assigned the return value of an expression protected by the Error Control Operator when the expression encounteres an error?

Based on the following code, the result is NULL (but it would be nice if this were confirmed to be true in all cases).

<?php

    $var

= 3;
   
$arr = array(); $var = @$arr['x'];    // what is the value of $var after this assignment?

    // is it its previous value (3) as if the assignment never took place?
    // is it FALSE or NULL?
    // is it some kind of exception or error message or error number?

var_dump($var);  // prints "NULL"?>


fy dot kenny at gmail dot com

2 years ago


* How to make deprecated super global variable `$php_errormsg` work

>1. modify php.ini
>track_errors = On
>error_reporting = E_ALL & ~E_NOTICE
>2. Please note,if you already using customized error handler,it will prompt `undefined variable`
>please insert code`set_error_handler(null);` before executing code, e.g:
>```php
>set_error_handler(null);
>$my_file = @file ('phpinfo.phpx') or 
>die ("<br>Failed opening file: <br>t$php_errormsg");
>```

>(c)Kenny Fang


manisha at mindfiresolutions dot com

8 years ago


Prepending @ before statement like you are doing a crime with yourself.

Joey

5 years ago


In PHP it is extremely beneficial to turn all notices into exceptions. This helps in creating bug free code through finding errors sooner rather than later. It also helps reduce the impact of bugs as code when entering an erroneous state ends sooner rather than later and at all. In the worst case without that you can have much more scenarios where code fails yet appears as though it succeeded.

However there are rare cases in which notices and warnings are produced where the above behavour might be unproductive. Worse yet your error handling will kick out that exception before the function gets to return.

They are rare cases such as socket handling where certain states are expressed through errors causing ambiguity.


Anonymous

9 years ago


I was wondering if anyone (else) might find a directive to disable/enable to error operator would be a useful addition. That is, instead of something like (which I have seen for a few places in some code):

<?phpif (defined(PRODUCTION)) {
    @function();
}
else {
    function();
}
?>

There could be something like this:

<?phpif (defined(PRODUCTION)) {
   
ini_set('error.silent',TRUE);
}
else {
   
ini_set('error.silent',FALSE);
}
?>


nospam at blog dot fileville dot net

16 years ago


If you want to log all the error messages for a php script from a session you can use something like this:
<?php
session_start
();
  function
error($error, $return=FALSE) {
      global
$php_errormsg;
      if(isset(
$_SESSION['php_errors'])) {
       
$_SESSION['php_errors'] = array();    
    }
 
$_SESSION['php_errors'][] = $error; // Maybe use $php_errormsg
 
if($return == TRUE) {
   
$message = "";
       foreach(
$_SESSION['php_errors'] as $php_error) {
         
$messages .= $php_error."n";
     } 
    return
$messages; // Or you can use use $_SESSION['php_errors']
 
}
}
?>
Hope this helps someone...

Anonymous

16 years ago


error_reporting()==0 for detecting the @ error suppression assumes that you did not set the error level to 0 in the first place.

However, typically if you want to set your own error handler, you would set the error_reporting to 0. Therefore, an alternative to detect the @ error suppression is required.


me at hesterc dot fsnet dot co dot uk

18 years ago


If you wish to display some text when an error occurs, echo doesn't work. Use print instead. This is explained on the following link 'What is the difference between echo and print?':

http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

It says "print can be used as part of a more complex expression where echo cannot".

Also, you can add multiple code to the result when an error occurs by separating each line with "and". Here is an example:

<?php
$my_file
= @file ('non_existent_file') or print 'File not found.' and $string = ' Honest!' and print $string and $fp = fopen ('error_log.txt', 'wb+') and fwrite($fp, $string) and fclose($fp);
?>

A shame you can't use curly brackets above to enclose multiple lines of code, like you can with an if statement or a loop. It could make for a single long line of code. You could always call a function instead.


How to disable errors just for particular php function, and in the same time to know that the error occurred? For instance, I use a php function parse_url, to parse an array of urls, sometimes it returns an error, what I want to do is to parse next url once error occurs, and not to show it(error) on the screen.

Jon Seigel's user avatar

Jon Seigel

12.2k8 gold badges57 silver badges92 bronze badges

asked Nov 5, 2009 at 16:14

spacemonkey's user avatar

0

You might want to take a look at set_error_handler().

You can do anything you want registering your own handler.

answered Nov 5, 2009 at 16:18

Seb's user avatar

SebSeb

24.9k5 gold badges66 silver badges85 bronze badges

the @ symbol before a function will suppress the error message and parse_url() returns false on erroring so just catch that.

 if(@parse_url($url) === false) {
        //Error has been caught here
    }

answered Nov 5, 2009 at 16:18

RMcLeod's user avatar

RMcLeodRMcLeod

2,5611 gold badge22 silver badges38 bronze badges

@ is evil.

You can use this:

try {
  // your code
} catch (Exception $e) {
  // a block that executed when the exception is raised
}

answered Nov 5, 2009 at 16:17

silent's user avatar

silentsilent

3,81323 silver badges29 bronze badges

2

the best way is to convert php «errors» to exceptions, using the technique outlined here http://php.net/manual/en/class.errorexception.php and then handle an Exception like you do in other languages:

 function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
 }
 set_error_handler("exception_error_handler");


try {
   parse_url(...)
} catch(Exception $e) {

answered Nov 5, 2009 at 16:19

user187291's user avatar

user187291user187291

53.2k19 gold badges94 silver badges127 bronze badges

Prefixing your function call with an @, so using @parse_url() should hide the error

answered Nov 5, 2009 at 16:17

Wim's user avatar

WimWim

11k41 silver badges57 bronze badges

3

To silent errors for a particular statement, simply add a @.

Example

$file = @file_get_contents($url);

When file_get_contents can throw error when $url is not found.

You can use the @ sign anywhere to silent any statements. Like:

$i = @(5/0);

answered Nov 5, 2009 at 16:17

mauris's user avatar

maurismauris

42.7k15 gold badges97 silver badges131 bronze badges

  • Konata69lol

Здравствуйте! Обычно для включения максимально подробного вывода ошибок я использую этот код:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

У меня вопрос. Чтобы отключить вывод ошибок вообще (если заливаю сайт на прод.), то нужен тот же самый код, только везде значения — 0? Или хватит только одной строчки? Если одной, то какая из них?


  • Вопрос задан

    более трёх лет назад

  • 18783 просмотра

В точке входа в проект (index.php), в самом начале выставить все по нулям

ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

Вывод ошибок лучше не выключать. Так вы лишите себя зацепок в случае багов на проде.
Для себя вывод подробностей ошибок перенаправляем в лог (файл/бд/другое хранилище).

Пользователю не нужно показывать подробности ошибок (стектрейс). Достаточно отобразить страницу с кратким описанием (понятным пользователю) ошибки, например «404 Не найдено то-то» или «500 Ошибка сервера».

Еще вариант — средиректить пользователя на главную страницу и флеш сообщением вывести краткое описание ошибки.

Я бы не рекомендовал затыкать вывод ошибок полностью, это bad practice. Пишу на PHP уже лет 10, и только недавно установил уровень E_ALL, исправление всех ошибок заняло где-то неделю, но сейчас я нарадоваться не могу, ибо ругается даже на отсутствие ключей в массиве (ибо в большинстве случаев если обращаются к какому-либо ключу, он должен быть в массиве, а его отсутствие — следствие какой-то проблемы). Об отсутствии какой-либо переменной я и вовсе не говорю. Для юзера достаточно просто подавить вывод ошибок (ибо сайт не будет работать только при E_FATAL и E_COMPILE, когда вообще не получается получить байткод), а для разрабов ошибки можно писать хоть в текстовый файл, используя собственный обработчик set_error_handler ().

Пригласить эксперта

Доступ к php.ini есть? Если да, то добавьте
display_errors = off

Можно ли как-то запретить вывод предупреждений, которые по сути не являются критичными, в поток, т.е. чтобы в логи все писалось, но в поток ничего не шло.
Данная ситуация сильно напрягает при асинхронных запросах к серверу, когда вместо ожидаемого ответа от сервера на клиента возвращается текст предупреждения.
Понимаю, что это наверное неправильно, но все же.


  • Показать ещё
    Загружается…

04 июн. 2023, в 12:07

2000 руб./за проект

04 июн. 2023, в 12:06

1000 руб./за проект

04 июн. 2023, в 12:06

30000 руб./за проект

Минуточку внимания

Можно ли в PHP отключить ошибки и когда это нужно делать

От автора: за свои ошибки нужно отвечать! Их нужно исправлять! Но ведь можно исправить как-нибудь потом, когда будет время? В настоящей жизни такое не всегда возможно, а на своем сайте для этого нужно лишь в PHP отключить ошибки.

Зачем прятать свои программные «недостатки»?

Тут, однако, «попахивает» философией, господа разработчики! А программирование и философия – это далеко идущие друг от друга дисциплины. Понятно, что если скрыть свои баги в коде, тогда будет не так стыдно. И никто не узнает, что вы только начинающий программист :).

В программировании желание убрать ошибки PHP не всегда говорит о непорядочности веб-разработчика. А скорее наоборот: таким образом он пытается обезопасить систему работающего ресурса от взлома и «не напрягать» пользователей отображением сообщений о существующих «недугах» в коде сайта.

Вывод ошибок приветствуется и востребован только на этапе «зарождения» нового ресурса. При его создании каждый из модулей движка должен пройти скрупулезную стадию тестирования. И все для того, чтобы затем корректно работать в составе всей системы.

С помощью сообщений, выдаваемых ядром языка, разработчик узнает о существующей проблеме. Дополнительно каждое уведомление об ошибке сопровождается коротким пояснением характера ее происхождения. Что позволяет разработчику как можно быстрее исправить допущенный «прокол».

Профессия PHP-разработчик с нуля до PRO

Готовим PHP-разработчиков с нуля

Вы с нуля научитесь программировать сайты и веб-приложения на PHP, освоите фреймворк
Laravel
, напишете облачное хранилище и поработаете над интернет-магазином в команде.
Сможете устроиться на позицию Junior-разработчика.

Узнать подробнее

Командная стажировка под руководством тимлида

90 000 рублей средняя зарплата PHP-разработчика

3 проекта в портфолио для старта карьеры

Отображение системных сообщений не только портит впечатление пользователей о ресурсе, но и делает его крайне уязвимым. Вот почему так важно отключать показ ошибок в PHP на работающем сайте.

Пример уязвимости

На следующем примере я попытаюсь доказать вам, что афишировать свои программные ошибки не всегда безопасно. Предположим, что сайт работает на каком-то движке, написанном с помощью MySQL и PHP. В одном из скриптов невыспавшийся кодер неправильно прописал пароль в строке подключения.

После запуска скрипта на сайте все пользователи увидят на экране описание данной ошибки. А хакер – получит логин пользователя без всякого взлома, «шума и пыли». Гляньте на следующий скриншот:

Закрываем дыру

В коде такую серьезную прореху можно «закрыть» с помощью «собаки». Точнее, символа «@». Пример:

@$load= mysqli_connect(‘localhost’, ‘root’, ‘321’, ‘site’);

Или с помощью функции error_reporting(), передав ей в качестве значения 0.

В первом варианте (с «собачкой») мы отключаем отображение ошибки, допущенной в одной строке. Во втором – запрещаем вывод уведомлений для всего кода скрипта.

Через файлы конфигурации

Кроме этого отключить ошибки PHP можно в htaccess. Данный файл содержит в себе настройки веб-сервера Apache. Чтобы системные сообщения о «багах» не появлялись на страницах ресурса, в данный фал следует добавить следующие строчки:

php_flag display_errors on

php_value error_reporting 0

Получается, что таким образом мы воздействуем не на отдельно взятый скрипт, а на весь код движка в целом. Но это не единственный способ глобального воздействия. Если вы используете Денвер, тогда в нем язык программирования работает в режиме шлюза (CGI). В таком случае нужно отключать ошибки в PHP ini. Найдите в данном файле следующую строку и измените значение директивы на off.

Профессия PHP-разработчик с нуля до PRO

Готовим PHP-разработчиков с нуля

Вы с нуля научитесь программировать сайты и веб-приложения на PHP, освоите фреймворк
Laravel
, напишете облачное хранилище и поработаете над интернет-магазином в команде.
Сможете устроиться на позицию Junior-разработчика.

Узнать подробнее

Командная стажировка под руководством тимлида

90 000 рублей средняя зарплата PHP-разработчика

3 проекта в портфолио для старта карьеры

Ну, вроде разобрались, как и когда в PHP нужно «отключать» свою совесть и запрещать отображение сообщений об ошибках. Причем в некоторых случаях это не только можно делать, но и нужно.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Php отключить отображение ошибок
  • Php отключить логирование ошибок
  • Php отключить вывод ошибок и предупреждений
  • Php отключить вывод ошибок htaccess

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии