Maison  >  Article  >  développement back-end  >  error_reporting() en PHP

error_reporting() en PHP

王林
王林original
2024-08-29 13:06:15201parcourir

Dans les différents niveaux d'erreurs de PHP, error_reporting est une fonction en PHP qui indique quelles sont les erreurs signalées et détermine la directive error_reporting lors de l'exécution. En utilisant cette fonction, nous pouvons définir le niveau prescrit pour la durée requise (généralement le temps d'exécution) de notre script. Il renvoie l'ancien niveau de rapport d'erreurs en fonction de l'entrée donnée, ou le niveau de rapport actuel lorsqu'aucun paramètre n'est donné.

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Syntaxe avec paramètres

Voici une syntaxe avec des paramètres :

Syntaxe :

error_reporting(level)

Paramètres :

Il n'y a qu'un seul niveau de paramètre qui est facultatif et dont la fonction d'entrée prend. Il spécifie le niveau de rapport d'erreurs pour le script actuel. Les valeurs acceptées sont le nom constant et le numéro de valeur.

Remarque : Pour garantir la compatibilité avec les futures versions de PHP, des constantes nommées sont recommandées.

Il existe quelques constantes prédéfinies dont la description est la suivante :

1. E_Error : celles-ci indiquent des erreurs d'exécution fatales qui ne peuvent pas être récupérées et l'exécution du script sera interrompue.

2. E_Warning : Il s'agit d'erreurs non fatales où l'exécution du script se poursuivra.

3. E_Parse : Cela affiche les erreurs d'analyse au moment de la compilation qui doivent être générées uniquement par les analyseurs.

4. E_Notice : Cela émet des notifications d'exécution indiquant que le script a trouvé quelque chose qui montre une erreur, mais qui peut également se produire lors de l'exécution d'un script normal.

5. E_Core_Error : Lors du démarrage initial de PHP, quelques erreurs fatales peuvent survenir et sont générées par le cœur de PHP.

6. E_Core_Warning : Ceci montre les erreurs non fatales qui surviennent lors du démarrage initial de PHP également générées par le noyau de PHP.

7. E_Compile_Error : ceux-ci affichent les erreurs fatales qui se produisent pendant la compilation. Ceux-ci sont générés par le moteur de script Zend.

8. E_Compile_Warning : similaires à ceux ci-dessus, ils affichent des avertissements au moment de la compilation ou peuvent être appelés erreurs non fatales et sont également générés par le moteur de script Zend.

9. E_User_Error : Ceci affiche les erreurs générées par les utilisateurs. Ceci est similaire à E_ERROR sauf qu'il est généré à l'aide de la fonction PHP dans le code PHP.

10. E_All : C'est comme une combinaison de tout ce qui précède qui prend en charge toutes les erreurs et avertissements sauf celui de E_STRICT.

Valeurs de retour :

La fonction error_reporting donne l'ancien niveau de rapport ou le niveau de rapport d'erreur actuel si aucun paramètre n'est donné.

Fonctionnement de error_reporting en PHP

Cette fonction permet au développeur de contrôler réellement les différents types d'erreurs et le nombre d'erreurs qui seront générées dans l'application. Cette fonction définit une directive error_reporting qui sera présente dans le fichier de configuration PHP ini .

error_reporting(0);
  • When 0 is passed to the error reporting function it removes all warnings, errors, parse related messages and notices, if any. Instead of having to include this line in each of the PHP code files, it is practical to have it added and to turn off these report messages in the ini file present or in the .htaccess.
error_reporting(E_NOTICE);
  • In PHP the variables can be used even when not declared. But this practice is not feasible as the undeclared variables may cause application related issues if it is used in conditional statements and loops. This may also take place because of the spelling mismatch between the declared variables and of that being used for conditions and loops. When this E_NOTICE will be passed into the error_reporting function, only then these undeclared variables will be shown in the web application.
error_reporting(E_ALL & ~E_NOTICE);
  • This error reporting function helps to filter out the errors which can be displayed. The “~” character here means the “not/no” and hence ~E_NOTICE here means to not show any notices. Here the “&” character represents “true for all” whereas “|” means as long as one of the parameters is true. They are exactly similar to the functions AND and OR in PHP.
error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);
  • All of the above lines serve the same purpose i.e. show all the errors. E_ALL is the most widely used function among all others by developers to display error messages as it is more comprehensible and intelligible.

Error Logging in PHP using error_log() Function

It happens so that during the production phase, error messages are to be hidden from the end-users but this information is needed to be registered for tracing purpose. And the best way to record these errors on the production web application is to write and store in log files.

An easy way to log these is by using the error_log function which takes our parameters as input. The only mandatory parameter here is the first one which contains details about the errors and what all to be logged. Other parameters like the type, destination, and header are non-mandatory here for this function.

error_log("Error found!", 0);
  • The type parameter will be set to 0 by default if not given, and the log information will be appended at the end of the log file generated in the webserver.
error_log("Error information being emailed!", 1, "[email protected]");
  • The type parameter here is 1 will email this log specified in the 3rd parameter which is the email id. For this to work, the PHP ini file must be having a correct SMTP configuration to send out emails. Some of the parameters required for these include host, encryption type, port, password and username.
error_log("Write errors to this file", 3, "https://cdn.educba.com/tmp/errorfile.log")<em>;</em>
  • The same error logs can also be written down to the required file whose path will be given in the third parameter. Make sure the given path has all required permissions.

Example of error_reporting() in PHP

Given below is the example:

Code:

<?php
$a = 1;
trigger_error("user warning!", E_USER_WARNING);
$a = 2;
echo "Value of $a is ${$a}";
error_reporting(0);
error_reporting(E_ALL);
?>

Output:

error_reporting() en PHP

Advantages of using error_reporting function in PHP

  • error_reporting is good for debugging purposes and for developing web application.
  • Each and every error can be logged and fixed as soon as it happens using this function.
  • To not show it to the end-user, make sure you redirect the errors to a log file while releasing it.

Conclusion

Hence we can say that error_reporting() function in PHP are therefore helpful in cases when there are a lot of problems with the PHP web application and we need to display all of these errors and warnings either for development or debugging purposes. It is a function we can enable different kinds of warnings or error messages and most of them are as discussed above.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:Exception personnalisée PHPArticle suivant:Exception personnalisée PHP