Suppressing PDO Warnings

纵饮孤独 提交于 2019-11-29 14:22:49

The only thing I can see here, is that you tell PDO to throw exceptions after you have tried to open the connection. That is most likely too late.

What you could do instead, is send that option 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) {
...

That will probably solve your problem.

Edit: If the host name is provided by the user, you could validate 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
}

That will work for domain names, localhost and ip addresses.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!