PHP新手求助:如何在浏览器中显示或隐藏错误?
Hey there! As a fellow PHP developer who remembers the early days of staring at blank browser screens wondering what went wrong, I totally get why you’re asking this. Controlling error display is a foundational skill—vital for debugging during development, and crucial to secure your site once it’s live. Let’s break down exactly how to handle both scenarios.
Showing PHP Errors in Development
When you’re building and testing your code, you want every error, warning, or notice to pop up so you can fix issues right away. Here are three common ways to make that happen:
Modify your php.ini file (the most permanent solution):
First, find where your php.ini is located by runningphpinfo()in a test script and looking for the "Loaded Configuration File" line. Then open it and update these settings:display_errors = On error_reporting = E_ALLdisplay_errorstells PHP to send errors directly to the browser, whileE_ALLensures you see every type of issue—even small notices that might cause problems later.Set dynamically in your PHP script:
If you don’t have access to php.ini (like on shared hosting), add these lines at the very top of your script:error_reporting(E_ALL); ini_set('display_errors', 1);These lines override the server’s default settings just for that script session.
Use .htaccess (for Apache servers):
If you’re using Apache, create or edit a.htaccessfile in your project’s root directory and add:php_flag display_errors on php_value error_reporting E_ALL
Hiding PHP Errors in Production
Once your site is live, you never want errors to show up in the browser—they can reveal sensitive code details to attackers and confuse regular users. Instead, log errors to a file so you can fix them privately.
Update php.ini for production:
Edit your php.ini with these settings:display_errors = Off log_errors = On error_log = /path/to/your/error.logMake sure the
error_logpath is a location your server has permission to write to. You’ll need to check this file regularly to catch and fix issues.Dynamic script settings:
Add these lines to your production scripts (or your main include file):error_reporting(0); // Turn off all error reporting ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', '/var/log/php/production_errors.log');.htaccess for Apache production:
Update your.htaccessfile to:php_flag display_errors off php_flag log_errors on php_value error_log /path/to/production_errors.log
Quick Tip
In development, don’t skip those notices or warnings—they’re often hints about code that might break later. In production, always log errors so you can troubleshoot without exposing your site’s inner workings.
内容的提问来源于stack exchange,提问作者sandip bharadva

