I'm wondering, if mysqli_connect() does automatically close at the end of the script. I know, that mysql_connect() does, but I'm speaking about improved mysqli_connect().. Also I found answered question, that says it does, but in official documentation it is not written.. So, can I rely on those not official statements? (Or better to ask, it is safe to rely on them?)
Here's what you should consider. The MySql connection does automatically close when the script terminates. However, if your script does a lot of processing after the data has been retrieved and stored to an array or whatever you store it to, it is safer to close the connection explicitly so you do not face the chance of running out of available connections while the script is busy running the post data retrieval routines. For me, I just explicitly close the connection. It's a habit I've developed and my fingers auto-type the command.
Related
What is the risk of using php's auto_append_file to automatically add:
session_write_close();
mysql_close();
To all files?
In working with a customer's application, I found that sessions and database connections were hanging open for some reason. As a quick fix, we added the code above via the auto_append_file.
This immediately resolved the issue of Apache threads staying in the Sending Reply state and reduced server loads considerably.
We are considering using this technique more often when the customer lacks sufficient resources or time to find the problematic code and fix it.
Edit
The question is not about best practices. I fully understand that this should not be required but I can reproducibly show the a reduction of hung Apache processes with this code added. The question is about the risk or negative impact would such functions cause.
From the documentation for session_write_close():
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time.
And from the documentation for mysql_close():
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.
Also worth noting from mysql_close(), using no link identifier...
If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no connection is found or established, an E_WARNING level error is generated.
Keeping all of the above in mind:
Calling the above functions shouldn't be necessary as they're automatically handled when a script terminates.
Calling mysql_close() in a script will only a) close the most recently opened link or b) throw a warning because no links were ever opened.
If you need scripts to give up resources as soon as they're done with them, using auto_append_file won't help you because of point #1. You'll need to modify the scripts themselves.
Database connections hanging open is a sign of a hung or long-running script. If the script terminated, then the database link should have as well. (Again, point #1)
As mentioned in the comments the driver should close the connection and the session is written and closed at the end of the script's execution anyway.
Also, you should be using mysqli or PDO, not mysql! (MySQL extension is deprecated as of PHP 5.5.0)
Anyway, a better idea when you want to do that kind of thing (execute something right at the end of the script) would be to register a shutdown function to do it (DRY):
http://www.php.net//manual/en/function.register-shutdown-function.php
(And an even better one is to keep track of whatever resources you are using and release them right at the point where you know your program will not be needing them any more. It's more efficient, and leaves no doubt about what's happening with them.)
Just learning php and aiming to write quality code.
I read everywhere that you should close all database connections to reduce vulnerability of your system. It's okay, but why and when?
Connections are closed automatically at the end of runtime. So questions are:
Can anyone please refer to me a resource that explains how an open database connection can actually be exploited? And for how long can it safely be open?
What is the difference if I close it with the last line of my application or leave it for the shotdown handler?
Some worth-reading description on the topic would be welcome.
Here are 3 simple tips that will help improve the security profile of your code, when it comes to databases:
Use PDO or mysqli, and don't use mysql.
Use prepared statements, always.
Never trust user input.
Database connections are not a real worry because:
They are automatically discarded at the end of your script, unless you are using persistent connections.
The database server will not let you hold on to an open connection indefinitely.
There is a limit on the database server on how many open connections are allowed. After this limit is exhausted, the database will refuse new connections with an appropriate message to the client.
Does the phpdriver for mongoDB provide a feature for starting the connection on demand - only.
Maybe this can save some load, although persistent connection is already really fast.
However, if there is a chance to optimize the application, i'd try this, too.
The alternative, calling the function to connect only on demand seems to be a bit tricky and makes my source very redundant.
The link H Hatfield posted addresses this question. Mongo::__construct() has a connect option that defaults to true, but you can specify false to delay the connection. The documentation isn't clear how lazy this is, as it only guarantees that the constructor will return without waiting for a connection to be established.
That said, you would be better off relying on persistent connections, which are being actively improved. I wouldn't be surprised if the lazy connection option was removed in a future major version of the driver.
On the documentation page when initiating the Manager it says:
this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed. So this is actually what you need already.
When I load a php page on my browser, it connects to the DB and runs some sql... let's say I now follow a link and it takes me to another page within the same website. What happened server wise? Did my first connection to the DB close, and re-opened again? Is that what happens in most cases?
Its very likely that the connection to your database is closed once the page has been processed by PHP, obviously then the result of the PHP is sent to the browser and viewed by the user.
Assuming you're running MySQL the only reason this wouldn't be the case is if the PHP script uses mysql_pconnect, where the connection will be kept open. However its usually good practice not use use this unless the MySQL server and the PHP server have a low bandwidth connection that's unused by other processes.
Yes, in most cases your database connection will close and re-open. In particular if the PHP interpreter is restarted for each page then it has no choice but to do this.
I believe the typical exception (although I've never used this myself) is where you're using something like mod_php.so (for Apache) and you arrange for a DB connection object to be stored as part of the user's session state. I don't believe that's recommended practise, though.
See http://php.net/manual/en/features.persistent-connections.php for more.
That's the usual case yes. But if you're talking about MySQL, you can use mysql_pconnect to keep persistent connections.
It depends on how the PHP was developed. If it was coded to close after each transaction, then yes it will be re-opened each time you view a page.
There is also the concept of a database connection pool. When a connection is used it is not closed but placed into a "pool" of connections waiting to be used again. Once a specified amount of time is passed without the connection being used it is then closed to save resources.
Pooling connections saves on processing time having to reopen a connection on each page reload.
I had never heard of persistent connections before, and I don't understand the advantages.
I run a PHP/MySQL based website, it receives tens of thousands of page views per day. In my header file on each of these pages I have just used mysql_connect() and I haven't bothered with terminating the connection in the footer file.
In my case are there any advantages of using mysql_pconnect()?
Using a persistent connection leaves the connection open after the script has finished executing. Opening and closing connections over and over causes overhead, while small, that will eventually mount up as the number of requests go up.
However, if you read the manual page for mysql_pconnect it states:
If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.
If this is the case it may not be worth the trouble changing your code.
You can find more detailed information on persistent connections at the same site as above.
Check out this URL:
http://us3.php.net/manual/en/function.mysql-pconnect.php
Basically mysql_pconnect() tries to find a persistent connection already open with the credentials that you've specified. If it doesn't find one it makes a new one. It also doesn't close the connection after a statement is executed
So really in your case you may not notice a difference but in reality you should probably be using mysql_pconnect().