views:

218

answers:

3

I've got an instance of a DB object that's passed to a Session object, because the Session object has several methods that make use of DB object to execute SQL statements I had plan to store this DB object in Session object property.

Through testing I found that print_r exposed the DB object stored in the Session object property; included in the output was the db user/password.

So my idea was to store the DB object in a private static member, to prevent this info from being disclosed whenever print_r is called on the Session object.

Is this acceptable, or just plain bad use of static member?

What's recommended way of preventing private object property from disclosed during print_r?

Here's code sample.

Before:

class Session 
{

    public __construct(DB $db)
    {
        $this->db = $db;
    }

}

After:

class Session
{

    private static $db;

    pubic __construct(DB $db)
    {
        self::$db = $db;
    }

}
A: 

Yes, this is bad

print_r() should only be used for debugging and not for displaying content to the user.

If the class contains secret information that schould not be visible to the tester, you have to sanitise (set the fields to empty string or something) the parts that are secret.

port-zero
+3  A: 

You can't stop print_r/var_dump/var_export from being able to read these, it has been reported several times to the php team but they consider it a feature (...) :

http://bugs.php.net/bug.php?id=39118&edit=2
http://bugs.php.net/bug.php?id=35822&edit=1

If you use a static member like in your exemple, please remember that every Session instance can access it/has the same; this can lead to some surprises later on.

Another idea is to wipe out the login/pass from the DB object once connected, this can help containing the issue.

Lepidosteus
It looks like the bug reports you linked are referring to private variables, not private static variables. I believe that static variables are not accessible from print_r/var_dump/var_export.
Joe Lencioni
A: 

Another approach is to modify the way that you're using the DB object. If a session method needs use of the DB object, they should call "global $db;" at the start of the method to ensure that sensitive DB login information is not actually part of the $_SESSION object of persistent data, and it's up to the calling page to have a proper $db object defined and not expose it during the life of that script's execution, without worrying about it hanging around in a SESSION object.

MidnightLightning