Let's say I do a odbc_connect call, deliberately using erroneous information, as follows:
<?PHP odbc_connect('bogus','bogus','bogus'); ?>
Now, the manual states that odbc_connect "[r]eturns an ODBC connection id or 0 (FALSE) on error". I'm okay with the 0 being returned, but when I'm running the file (using Wampserver), I also receive error messages telling me that something went wrong.
I would like to suppress this error message, since I'm trying to build a PHP file that only echoes a certain piece of text, like "unsuccessful", when the information for the database call was wrong.
Use a try-catch:
<?php
try {
odbc_connect('bogus', 'bogus', 'bogus');
} catch (Exception $e) {
// handle your exception
}
You can also use # to suppress error messages on a single line - but it isn't good practice.
<?PHP #odbc_connect('bogus','bogus','bogus'); ?>
Error messages are there for a reason, don't ignore them. Use something like #Matt suggests and trap them as needed - not just hush them up.
You can use the error-suppression operator #.
<?php
$conn = #odbc_connect('bogus','bogus','bogus');
?>
Related
I have to include database connection in some PHP scripts. So I require() first and then put my queries after. If viewed as a single script, it amounts to something like this:
Try {
$connect = new PDO("mysql:host={$DB_host};dbname={$DB_name}; charset=utf8mb4",$DB_user,$DB_pass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Catch(PDOException $e) {
echo $e->getMessage();
}
// Then I put the queries here
It works, but my question is: is this safe? I've seen in most tutorials that they put all the queries within Try { } curly brackets. And what is the difference between putting the queries within Try { } and putting it after ?
If for whatever reason your query fails the program will crash at the line of code that was executing the query. There may be justification to do this if this a behavior that you desire in your code, for whatever reason.
Without the error handling your program will just break whenever an error is thrown. So unless you specifically need to have the query outside of the try catch (I couldn't guess what for), then you will just be creating trouble for yourself in the future.
If an exception occurs during your query (For instance, if it can't execute the query properly because of a missing quote), the error will not be caught and the execution of your script will halt.
Error handling is usually always preferred when possible. If there is a problem fetching data, inserting data, or simply a typo in your query, you should always have a way to notify a user that an error has occurred (And also, log it for further investigation for yourself.)
In my PHP aplication,I want that whenever -Internal Server or 500 error occurs,I want the error code to be changed from 500 to 302.I mean error code 302.
Try to use http_response_code.Also, take a look on related question How to return an HTTP 500 code on any error, no matter what.
i would not recommend you do that.
Instead wrap your code that is generating this error within a Try & Catch statement and try to handle exception there.
try {
// your code here
} catch (Exception $e) {
echo $e->getMessage();
}
I'm fairly new to PDO. I have a try and catch which catches and displays errors when something doesnt exist i.e a table.
However, how can i show the error message/cause for sql failed commands.
For example below i was trying to insert the word "enabled" into a tiny int column - however, only showed me a blank screen - had to debug myself. How can i show SQL failed error messages?
$db = new PDO('mysql:host='.$dateBaseHost.';dbname='.$dateBaseName, $dateBaseUsername, $dateBasePassword);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// set/get variables
$id = (isset($_GET['id']) === true) ? $_GET['id'] : die("ID not set") ; // ? : shorthand if else
$action = (isset($_GET['action']) === true) ? $_GET['action'] : die("Action not set") ; // ? : shorthand if else
// query
$query = $db->prepare(" UPDATE `telephoneCountries` SET `enabled`= :action WHERE `id` = :id ");
// bind parameters - avoids SQL injection
$query->bindValue(':id', $id);
$query->bindValue(':action', $action);
// try... if not catch exception
try {
// run the query
$query->execute();
}
catch (PDOException $e){
//sendErrorMail($e->getMessage(), $e->getFile(), $e->getLine());
echo $e->getMessage();
echo $e->getFile();
echo $e->getLine();
}
i was trying to insert the word "enabled" into a tiny int column
it's fairly OK to mysql. 0 will be inserted.
how can i show the error message/cause for sql failed commands.
for the real errors you have to just setup PHP to display them
ini_set('display_errors',1);
so - you'll be able to see every uncaught exception.
Also, if you are only going to display an error message, but not handle the error itself, just don't use try..catch at all. PHP will do all the job already. That's the point.
Most people do confuse error reporting with error handling. The latter shouldn't be used for the former. When dealing with error messages, your only goal is to make PHP to raise them, and to set up the proper destination:
on a development server an error message have to be show on-screen
on a live sever it shouldn't be shown, but logged instead.
without all these try-catch blocks you'll be able to control error messages (including non-exceptions) by means of a couple ini settings or single error handler function (which I mentioned to you in the other answer).
use try..catch only if you are going to handle the error itself - say, to connect to another server for example.
So, to answer your question more verbosely:
Set PDO in exception mode. Done already.
Remove all try..catch blocks that deals with error messages only.
Setup PHP to show errors on a development server using ini directive above.
On a live server it is strongly recommended to log errors instead of emailing them. But if you still want it this way - use single custom exception handler function to send emails instead of hundreds try..catch blocks
I'm running a PHP script every night using a cron service. Everything it outputs will be printed to an log file for debug prepossess. The file I use will retrieve xml's from a different site using the function 'file_get_contents()'. But the function can return an error which I really don't want to see as I am already showing a custom error.
Quick example of my piece of code:
$buffer = #file_get_contents('http://xx:xx#xx/xml/xx?offset=2') or print('retry in 5 seconds');
if($buffer === false) {
sleep(5);
$buffer = #file_get_contents('http://xx:xx#xx/xml/xx?offset=2') or print('error notice');
}
The problem is the first one will trigger an error and print it'll retry in 5 seconds. How can I correctly suppress the thrown error?
I have an error handler, but I prefer not to catch this error separately.
Edited:
My solution wasn't to change the error_reporting, but to catch the error message. If it starts with 'file_get_contents()', no error will be thrown. This is not the best way, but will do the job for me.
You can try inserting this at the start:
error_reporting(0);
Then after the code with the error/warning:
error_reporting(E_ALL ^ E_WARNING);
Okay, never ever use the #-operator.
In PHP you have two options available: either use a custom error handler or use try/catch.
Since file_get_contents doesn't throw an exception, you can only use the first approach.
You can set an error handler like this: http://php.net/set-error-handler and then act correctly (log something or return a custom error code).
If you just want to turn of all errors use error_reporting(0) or if you just want to turn off a specific category use error_reporting(E_ALL ^ E_WARNING) (all but warnings) or specifcy them explicitely error_reporting(E_WARNING | E_NOTICE) (warnings and notices).
I prefer the first approach, since when you just disable it you have no idea of what's going on in your code.
Add # before command or use try catch.
I'm trying to include a file, and catch it if the file does not exist / can not be opened. I would have thought that a simple try/catch statement would have worked but PHP seems to completely ignore it, and error out.
Any ideas? I know there are other questions like this on stackoverflow, I've seen them, but none of them seem to have a proper, working answer.
You can check the return value of include to see if it failed or not:
if((#include $filename) === false)
{
// handle error
}
You'll note I included the error suppression operator (# ) to hide the standard error messages from being displayed.
Since include() returns false when fails, just check if it returns true and then do something like die() or show an error.
if (!include('page.php'))
die('Error.');