PDO warning suppression

I am trying to display server status based on whether a database can be connected or not. With the old school, mysql_connect() and mysqli_connect() was easy. I try to stay up-to-date, so I use PDO, but I cannot figure out how to suppress the default warning. From what I can say, you need to use the getMessage() function so that it prints a PDO warning, but I do not use it.

Here is my code:

 8 $dbstatus = 1; 9 try { 10 $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd); 11 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 12 } catch(PDOException $e) { 13 $dbstatus = 0; 14 } 15 if($dbstatus == 1) { 16 echo '<span style="color: green">DB Up</span>'; 17 } else { 18 echo '<span style="color: red">DB Down</span>'; 19 exit; 20 } 

All connection variables are supplied and corrected, with the exception of $dbhost , which is intentionally broken to verify this. Now it gives the desired results, but also displays a warning message:

Warning : PDO :: __ construct (): php_network_getaddresses: getaddrinfo failed: this host is not known. in C: \ xampp \ htdocs \ cd \ includes \ dbconnect.php on line 10

If I fix the $dbhost variable, it works fine, so I know that the problem is not that the PDO instruction can be used.

Any ideas on what I am missing?

Decision

I used a variation of what was given by jeroen:

 if(filter_var(gethostbyname($dbhost), FILTER_VALIDATE_IP)) { $dbstatus = 1; try { $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } catch(PDOException $e) { $dbstatus = 0; } } else { $dbstatus = 0; } if($dbstatus == 1) { echo '<span style="color: green">DB Up</span>'; } else { echo '<span style="color: red">DB Down</span>'; exit; } 

Thanks for the help and I hope this helps someone else! ^^

+5
source share
1 answer

The only thing I see here is that you indicate that PDO throws exceptions after you try to open the connection. Most likely it's too late.

Instead, you can send this parameter to the constructor directly using the 4th parameter:

 try { $opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd, $opts); } catch(PDOException $e) { ... 

This will probably solve your problem.

Edit: If the host name is provided by the user, you can verify it before sending it to the PDO constructor.

For example, using:

 if (filter_var(gethostbyname($user_provided_host_name), FILTER_VALIDATE_IP)) { // valid hostname / ip address } 

This will work for domain names, localhost and IP addresses.

+2
source

Source: https://habr.com/ru/post/1205376/


All Articles