views:

151

answers:

4

I was just wondering what security issues can arise from not closing the database connection after using it. Doesn't PHP automatically close it once a new page loads?

Levi

A: 

I can't say whether or not the page closes the connection (that would depend on whatever is managing it) but in general, it is a good idea to close it when you are done because leaving it open longer will potentially cause a starvation issue for other pages that are processing at the same time which want to connect to the same data source.

casperOne
Especially if the app is using connection pooling.
Paul Tomblin
+4  A: 

As the mysql_close() documentation says:

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Since the connections are managed by PHP there shouldn't be a security risk.

Greg
+1  A: 

PHP is supposed to be a "shared nothing" architecture. That is, all resources are allocated for every request, and then cleaned up after the request is finished. So resources like memory, file handles, sockets, database connections, etc. should be deallocated or closed.

However, you can use persistent database connections which are not closed, but are re-used for the next request. If you do this, there is some security implication. Any connection state is inherited by the next PHP request. So if your application uses database user-defined variables, or temporary tables, or even LAST_INSERT_ID(), the next PHP request may be able to see privileged data that it shouldn't see.

If you close the database connection to avoid this, you're basically defeating the value of the persistent connection. So you might as well use plain database connections.

Bill Karwin
A: 

Jeff Atwood wrote an interesting blog post on this very subject that you might find interesting.

meouw