Php 5.6 to 7.3 conversion & security help needed

#1

I have been struggling with a very old year make and model script. Its not very large at all and i think i have the connection.php almost straight. Here is what i started with.


<?php
mysql_connect("localhost", "db_uname", "db_pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
?>

This is what i have now/


<?php
// Create connection
$conn = new mysqli('localhost', 'db_uname', 'db_pass', 'db_name');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

I wanted to do PDO but i’m not up to speed with that. Do you think this is secure?

Thank you in advance

#2

No. Unconditionally outputting connection errors on a web page gives hackers useful information -

  1. That they were able to caused a connection error, i.e. too many connections.
  2. A connection error contains the connection username, giving them half the information they need to break into your database.
  3. The error contains server path information, which can be used to find other ways of compromising your server.

Instead, use exceptions for database errors (connection, query, prepare, and execute) and in most cases let php catch the exception, where it will use its error related settings to control what happens with the actual error information (database errors will get displayed or logged the same as php errors.) The exception to this rule is when inserting/updating duplicate user submitted data. In this case, your code should catch the exception, detect if a duplicate key error occurred, and setup a user error message for the duplicate value.

If you are updating old code or writing new code, PDO is the simplest and most consistent way of doing so, since you must either convert or add protection against sql special characters in external/unknown data from breaking the sql query syntax (which is how sql injection is accomplished.) The following is typical PDO connection code -

<?php

$DB_HOST = 'localhost';
$DB_USER = '';
$DB_PASS = '';
$DB_NAME = '';
$DB_ENCODING = 'utf8'; // db character encoding

$pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to exceptions
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // run real prepared queries
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); // set default fetch mode to assoc

The PDO connection always uses exceptions. The above code sets the error mode to exceptions for all the other database statements.

2 Likes
#3

That was quite the post! Thank you for making me aware of a proper pdo connection. I am way over my head on this small script. It only has a couple of files so i think i would be better getting a dev to look at the whole thing. Maybe i should post in the freelance section. phdr you rock man!