Reputation: 454
I have written a supersimple code to track my blog's activity. I'm including this file on every page at the very begining:
<?php
session_start();
if ($_SESSION["i"] == "") {
$_SESSION["i"] = rand(0,9) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90));
}
$r = $_SERVER['HTTP_REFERER'];
if ($r == "") {$r = "Direct";}
$u = $_SERVER['REQUEST_URI'];
include ($_SERVER['DOCUMENT_ROOT'].'/db.php');
$stmt = $conn->prepare("INSERT INTO analytika (id, page, referrer, visit, time) VALUES (DEFAULT, ?, ?, ?, DEFAULT)");
$stmt->bind_param("sss",$u,$r,$_SESSION["i"]);
$stmt->execute();
$stmt->close();
$conn->close();
?>
Problem is, what do I do to prevent echo's from PHP when error occures?
I've found error_reporting(0);
but that obviously isn't the solution, because my page wont load further the error. And since im including things into DB, problems may really occur.
So, how do I rewrite my code to skip itself if something goes wrong and the page loads on as it would normally? Thanks PHP 7.0
Upvotes: 1
Views: 1640
Reputation: 4288
When you're using PHP in production, it's highly recommended not to show exceptions and errors, and even notices and warnings. To prevent showing these bad characters, you have to change display_errors
option in php.ini file (see the link for more details).
However, there's another option. For instance, if you could not change ini file, you can use ini_set()
function on every page you want to disable error reporting. But there is a problem with ini_set()
; from php.net:
Note: Although display_errors may be set at runtime (with ini_set()), it won't have any effect if the script has fatal errors. This is because the desired runtime action does not get executed.
Also, to track errors, you can set log_errors
and error_log
options, by changing php.ini or using ini_set() function.
Upvotes: 0
Reputation: 653
You would typically use a try/catch block to handle errors that you think may occur e.g. "what do you want to happen if your database is unavailable?" https://www.w3schools.com/php/php_exception.asp
In PHP you can suppress error messages using the @
operator. Again though it's recommended that you handle errors. This wouldn't prevent an error in your script from stopping execution.
http://php.net/manual/en/language.operators.errorcontrol.php
Upvotes: 1