3

I am a bit worried when I incidentally var_dump() the object of a child class, the result showed all my sql elements and variable values including database username,password and DBname. Is there a security issue with it. If yes how do I shield it? Would be thankful if someone show me a light on it.

$ClassObject=new MyChildClass();
var_dump($ClassObject);

A sample result is as follows:-

object(MyChildClass)#1 (17) { ["database":protected]=> object(Crud)#2 (13) { ["rows"]=> string(12) "column_name" ["vals"]=> NULL ["query"]=> NULL ["table"]=> string(8) "users" ["DB_TYPE":"Database":private]=> string(5) "mysql" ["host":"Database":private]=> string(9) "localhost" ["user":"Database":private]=> string(4) "root" ["pass":"Database":private]=> string(7) "mypass" ["db":"Database":private]=> string(13) "mydbname" ["conn":"Database":private]=> object(PDO)#3 (0) { } ["error":"Database":private]=> NULL ["result"]=> NULL ["stmt":"Database":private]=> object(PDOStatement)#5 (1) { ["queryString"]=> string(51) "SELECT column_name FROM ms_users WHERE userid=:uid" } } ["loguserid":"Users":private]=> string(1) "4" ["rows"]=> array(0) { } ["vals"]=> NULL ["query"]=> NULL ["table"]=> string(16) "MyTable_name" ["DB_TYPE":"Database":private]=> string(5) "mysql" ["host":"Database":private]=> string(9) "localhost" ["user":"Database":private]=> string(4) "root" ["pass":"Database":private]=> string(7) "MyPass" ["db":"Database":private]=> string(13) "mydbname" ["conn":"Database":private]=> NULL ["error":"Database":private]=> NULL ["result"]=> NULL ["stmt":"Database":private]=> NULL ["join"]=> string(0) "" ["where"]=> string(35) "user_id=:id1 AND column_name=:id2" }

pah
  • 4,700
  • 6
  • 28
  • 37

1 Answers1

4

The magic method __debugInfo does just that. In your class, add the following code:

public function __debugInfo()
{
    $properties = get_object_vars($this);
    unset($properties['host']);
    unset($properties['user']);
    unset($properties['pass']);

    return $properties;
}

How it works: the first line retrieves the full list of properties in the current instance. Then, with unset, we remove all the properties we don't want displayed by var_dump.
Modify the code to remove from $properties all the properties you want to hide.

In this first example, all properties except 3 will be displayed when using var_dump on this object.

Or use a safer way: create an empty array and populate it only with the properties you want displayed:

public function __debugInfo()
{
    $properties = [];
    $properties[] = 'table';
    $properties[] = 'queryString';

    return $properties;
}

In this second example, only 2 properties will be displayed when using var_dump on this object.

By adding this method to all your classes, you can control exactly what gets displayed when using var_dump.

Documentation: __debugInfo

Jocelyn
  • 11,209
  • 10
  • 43
  • 60