In the process of PHP development, we will inevitably encounter some program running errors. At this time, the system's default error message may provide opportunities for attackers. Therefore, in the actual development process, we need to shield error information to enhance the security of the website. This article will provide you with some reference by introducing the method of shielding error information returned by PHP.
PHP provides a method to turn off error reporting, that is, add the following line of code to the code:
error_reporting(0);
When using this method , PHP will not display any error messages, including syntax errors and runtime errors. This method is simple and easy to use, but developers cannot find and fix errors in time, so it is only suitable for officially launched websites.
Use this method to save the error information to the log file on the server side. The code is as follows:
ini_set('log_errors', 'On'); //开启日志记录 ini_set('error_log', '/var/log/php.error.log'); //将错误信息输出到指定路径的日志文件中
During the development process, you can use this method to quickly locate the cause of the error and fix it by viewing the log file when an error occurs.
Use this method to redirect error information to a custom page to achieve shielding. The code is as follows:
ini_set('display_errors', 'Off'); ini_set('error_reporting', E_ALL); ini_set('log_errors', 'On'); ini_set('error_log', '/var/log/php.error.log'); function myErrorHandler($errno, $errstr, $errfile, $errline) { header('Location: /error.html'); //将错误信息重定向至自定义错误页面 exit; //终止脚本的执行 } set_error_handler('myErrorHandler');
With this method, even if an error occurs, the attacker cannot see any useful information, thus improving the security of the website.
If your website uses Apache server, you can use .htaccess file for site-wide blocking. The following code redirects the error message to a custom error page:
php_flag display_errors Off //关闭错误信息输出 php_value error_reporting 0 //屏蔽所有错误信息 ErrorDocument 500 /error.html //设置500错误的自定义错误页面
This method is suitable for multiple PHP programs running at the same time. You only need to add the above code to the .htaccess file in the root directory of the website. .
Summary
The above introduces you to the method of shielding the error message returned by PHP. By choosing different methods, we can respond flexibly according to development needs. It should be noted that error message blocking is only a way to enhance website security and cannot replace other security measures. Therefore, during the development process, it is also necessary to combine other security measures to comprehensively improve the security and reliability of the website.
The above is the detailed content of Summary of methods for shielding returned error messages in PHP. For more information, please follow other related articles on the PHP Chinese website!