I am new to MySQL and PHP and am attempting to make my own CMS to help make managing my websites easier. Can someone explain mysqli's close() function?
Is it necessary?
What exactly does it do?
I heard that after PHP runs its script that it closes the
connection, is that true?
Lastly, is there a security issue when not closing your connection
to the database?
Is it necessary?
No, PHP will end your connection after it finishes running.
What exactly does it do?
The reverse of mysqli_connect() -- it closes the active DB connection.
I heard that after PHP runs its script that it closes the connection, is that true?
Yes, see the answer to "Is it necessary?"
Lastly, is there a security issue when not closing your connection to the database?
Nope, no security issue. The connection can't be hijacked by an outsider or anything like that.
However, since the number of total connections available is limited, freeing the resource the second you're done with it is considered polite to close it when you're done. This is likely why you've been told to close it when you're done.
You need to close the Mysql session when you manual set variables ##session or non-defined (set to ##session).
for example
$mysqli->query("SET #uuid=UUID()");
https://dev.mysql.com/doc/refman/5.1/en/set-statement.html
Related
I have this issue:
new MySqli
new Session - with the mysqli as parameter
$_SESSION Usage
close MySqli
But at the end, after I close MySqli, Session::_write is called. Can anyone tell me how can I securely close my MySqli connection after everything is done? Or I don't actually need to? I was thinking that every time the page is accessed a new MySqli connection is opened and never closed, which brings me to thinking I might get some kind of overflow sometime. Any Information would be much appreciated.
The PHP parser is only running when there is a script to process. How does it know when a script needs to be processed? Your web server sends them to it and outputs its data via http to the client. Every time the php process ends (end of script) it disconnects from the sql server, unless you've specified it to leave the connection open.
I would not be worried about it leaving the connection open due to the last Session::_write call, though I would call Session::write_close before closing the SQL connection if you are using it for sessions just to be safe and make sure all data is written back to the db.
I am accessing a database in a php script by establishing a connection using mysqli_connect function. I observe it is not mandatory to close the connection at the end of the script.
What are the implications of not using mysqli_close() in a connection script created to access mysql database in php?
If you are using cgi, then it is not necessary to close your mysql connections since they close automatically at the end of script execution.
From the documentation:
Note: The link to the server will be closed as soon as the execution
of the script ends, unless it's closed earlier by explicitly calling
mysql_close().
Although it is considered a good practice to close your connection.
If you close the connection yourself:
You have to check the value of $_connected for every single query. This means PHP has to check that the variable $_connected A) exists
B) is a boolean and C) is true/false.
You have to call your 'disconnect' function, and function calls are one of the more expensive operations in PHP. PHP has to check that
your function A) exists, B) is not private/protected and C) that you
provided enough arguments to your function. It also has to create a
copy of the $connection variable in the new local scope.
Then your 'disconnect' function will call mysql_close() which means PHP A) checks that mysql_close() exists and B) that you have provided
all needed arguments to mysql_close() and C) that they are the correct
type (mysql resource).
So if you are not using persistent connections, your MySQL connection will be closed at the end of the page execution. So you dont have to bother about that. And hence no downsides.
If you're fairly sure you're not going to use the connection again, or don't have a class that manages your open connections, closing is good practice. A couple reasons:
If you're looping or something over something that creates connections without closing prior ones, you could eat up all your available DB connections based on whatever limit is set on the sql servers side. Typically this limit is for everyone not per host, so you could prevent others from connecting as well.
From Zend (maybe dated): Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.
When I was writing PHP code with PDO and MySQL, I would always create connections when I needed them within functions like so:
result pseudo_function() {
create and open connection
do stuff
close connection
return result
}
Now, I started programming in C, I have seen that pointers are an interesting way to pass the entire connection as parameter to the function. I was wondering if it would be better to pass the connections between functions until the entire user request is served.
To clarify: For one user request, there could be 1-5 calls to a function that then opens a database, fetches data, does something, closes and returns.
Also does it make a difference performance wise if you keep a connection opened?
The "standard idiom" for most PHP code I've seen seems to be "open the connection, and leave it open".
php.net seems to be down at the moment, but these two links might be of interest:
http://php.net/manual/en/function.mysql-pconnect.php
http://php.net/manual/en/mysqlnd-ms.pooling.php
If you're running Apache, perhaps mod_dbd might be a good solution:
http://httpd.apache.org/docs/2.2/mod/mod_dbd.html
Here's a good discussion on the implications of not closing your connections:
Is it totally reckless to leave mysql connection open through a page?
It's better to keep a connection open and perform 5 operations on that connection than opening a new connection every time.
You can also lazy-load your database with a singleton repository pattern; the repository only opens a connection once, upon next invocations it will return a cached result.
If you develop web applications with PHP, it's common (and I suppose the most efficient way) to open the database connection once and close it when the script terminates. Keeping a connection open while other stuff is done does not really produce any overhead or require any actions at all, but reconnecting every time does.
I am a paranoid kind of guy and even though I included mysql_close() in my PHP functions after I do something, is there a way I can check (besides another query) to see if the connection is still open, just for assurance.
The mysql_close() function returns true if it succeeded. By adding an extra check outside of checking the return value of mysql_close(), you aren't doing anything helpful, and adding another place bugs can crop up in your code.
In any case, non-persistent connections are closed automatically when your script finishes, so it isn't necessary, unless you have some specific reason to kill off the resource ahead of time.
You may want to try mysql_ping()
Here is an excerpt from that page:
bool mysql_ping ([ resource $link_identifier ] )
Checks whether or not the connection to the server is working.
If it has gone down, an automatic reconnection is attempted.
This function can be used by scripts that remain idle for a long while,
to check whether or not the server has closed the connection and
reconnect if necessary.
Note: Since MySQL 5.0.13, automatic reconnection feature is disabled.
As for this excerpt, I do not know whether the automatic reconnection feature is disabled comment refers to mysql or PHP. You will have to experiment with it to find out. If this reconnection issue is indeed true, then #Brad's answer is paranoid-proof since you could run mysql_close immediately after querying the data and fetching it. You can be sure at that point that there is no valid connection since you explicitly closed it. Consequently, you would have to run mysql_connect for your next query.
However, letting non-persistent connections close on there own is not always a good idea because this could potentially stockpile TIME_WAITs in the DB Server's netstat. This would fool webservers into thinking that DB Connections are no longer available because MySQL ran out where the OS would actually be the cause since it would delay releasing Connection Resources. To be better safe that sorry, run mysql_close when done and mysql_connect/mysql_query for the next query.
If you are willing, you could construct a try-catch paradigm or a set of if-then-else stataments to first run mysql_ping on an established connection. If true, use it with mysql_query. Otherwise, run mysql_close/mysql_connect/mysql_query.
$con = mysql_connect("localhost" ,"name", "pass");
/* your code*/
if ($con){
mysql_close();
}
AFAIK if you open mysql connection with mysql_pconnect(), they don't really clossed after mysql_close(), it's just return to connection pool
I have a php application. There is a lot of database operation and i do mysql_connect() to open connection. Do I have to close the connection manually?
In general, after script execution the connections should close automatically. However in some cases (e.g. like yours) you have no other way but to do it manually (make mysql_close($connection) to be the last line of your script).
Alternatively, consider using mysql_pconnect() to have persistent connection, which doesn't close after script completion, and is (implicitly) reused on the next request.
Yes. But you do mysql_connect() many times. you can keep it in seperate file and include where ever needed.
Increase the number of allowable connection in mysql settings should do the trick i guess. But before that make sure on each page you are only opening the mysql connection once. At the end of the script the connection should automatically be closed, so no you dont really have to close it manually.
Use singleton to keep just one open connection on each page.