$this->close(); when to use [duplicate] - php

Do I really need to do mysql_close()? Why or why not?
Is there a trigger that closes the link after mysql_connect even if I don't do mysql_close?

According to the documentation:
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
Personally, I always like to make sure I pedantically close anything that I open, but it's not required.

In most cases calling mysql_close will not make any difference, performance-wise. But it's always good practice to close out resources (file handles, open sockets, database connections, etc.) that your program is no longer using.
This is especially true if you're doing something that may potentially take a few seconds - for instance, reading and parsing data from a REST API. Since the API call is going over the line, negative network conditions can cause your script to block for several seconds. In this case, the appropriate time to open the database connection is after the REST call is completed and parsed.
To sum up my answer, the two big rules are:
Only allocate resources (file handles, sockets, database connections, etc.) when your program is ready to use them.
Free up resources immediately after your program is done with them.

what's the benefit of closing the link?
The benefit is that you can free the connection to the database, and corresponding resources in the database server, earlier than the PHP request cleanup would do it.
Say for example you query all the data your request will need in the first 20 milliseconds of the request. But then your PHP code spends another 80 milliseconds running code and formatting the results. Which means 80% of the time, the app is holding open a db connection without needing to, and on average, 8 out of 10 connection threads on the db server are idle and using resources.

The manual says:
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
So, no, not really. It is helpful to free up resources before attempting an operation that potentially consumes large amounts of resources though, but it probably won't make a big difference.

what;s the benefit of closing the link?
Normally, there is no benefit in closing the link yourself, as it will be automatically closed.
I can only think of a couple of benefits
If your script has a lot of processing to do after it has finished using the database, closing the database link prematurely may help free up a little bit of memory and other resources (such as MySQL connections) while your script continues with other things. This is very unlikely to be an issue in most scripts, since most scripts will terminate pretty quickly after it has finished with the database connection anyway, and the time the connection is held open before the PHP script terminates will be comparatively short.
Completeness and cleanliness of code. It can give you a good feeling, and is generally good code hygiene to close what you have opened, even though in this case it isn't technically required.

Related

Security implications of ignore_user_abort() function

Has PHP's ignore_user_abort() function any security implication?
I'm thinking in DoS. For example, when having the function exposed to anonymous traffic in some code that is resource expensive.
As addition to the previous answer I'd like to add that the risk is not bigger, but is being shifted a little.
If the goal is to overload the server by calling an expensive script a lot of times, it is clear that calling ignore_user_abort(true); relieves the attacker from the need to keep the connection open. The script will continue to execute nevertheless of the connection status and consume resources.
In contrast without ignore_user_abort(true); the script would end its execution on the first output (if there happens no output the script will be as consuming as the first variant [1]).
In case of a DoS attack (and especially a DDoS attack) the attacker likely has absolutely no problem in opening (and holding open) a lot of connections. Therefore from this perspective ignore_user_abort makes no difference.
I can't think of any further security related implications of using this functionality.
I would even claim that most PHP developers do not really know that the execution of their scripts might stop somewhere in the middle just because the connection is lost. I think most would guess that their scripts will execute until the end in all cases although this is not the default setting.
I don't see any direct security implications with ignore_user_abort() function .
In terms of DoS attack , considering the containing script is
resource expensive
exposed to anonymous traffic
the concern should be of server overload which could lead to temporary or indefinite interruption or suspension of services .
If possible it would be wise to find alternatives for such a resource expensive code :
If the containing script is used to simulate cron task , it would be wise to use crontab instead .
If possible it would be wise to put programmatic restriction in place to run only one instance of such resource expensive code irrespective of how many page hits the containing script would get .
Hopefully this is of some help .

How to organize the handling of database connections within functions?

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.

What happens if MySQL database wasn't closed?

What happens if MySQL database is not closed? How do we know if it is closed properly?
I do have a page which has 11 tables on a page..so what I did is I open database on top of page before script starts and close where the scripts(PHP) ends...
the ending is mysql_close($db);...is this fair enough or do I need to give only mysql_close();
I can't say for sure if all PHP/Mysql versions on all server platforms behave the same way. For tcp connections to the database - unless you call mysql_close($db), you'll have a dangling tcp connection just sitting there waiting to be used for half a minute after the script ends. Then it'll just go away on its own.
I can't say if this is PHP's garbage collection taking a full 30 seconds to complete, or if the tcp connection is set to expire after 30 seconds on its own once you call connect.
Mysql_close($db) instantly kills the tcp connection though. So yeah, I'd say always call mysql_close($db) immediately after you no longer need a database connection in your script.
There isn't a point in closing a connection at the end of the script because that is done for you when the script terminates. The only time you should really call the close function explicitly is if you're running a daemon or something and don't want to hold onto a connection for the entire run length.
PDO is considered the modern database access library for PHP (you really should be using this instead of the mysql_* functions, but that's another story) and even that doesn't have a close function, just to drive the point home.

Where and when to open a database connection

I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?
Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer. If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer. The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one. This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.
Well, if you are using a class, the connection should be opened automatically when you instantiate the class, or when the first query is performed. If you never use the class, the connection wouldn't be opened. While it is good practice to close it when you don't need it, it doesn't hurt to let it be closed when the request thread dies.
This can be bad if you don't have a resource limits set in your php.ini file, the request could possible live forever and never close the connection.
If you have a medium-to-high traffic site, you should be thinking about using mysql_pconnect anyways so there is always a connection open and you don't need the overhead of opening one on every request.
Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.
That being the case, you should only open the connection before you want to run your queries. If you have a large number of queries, try to open your connection as late in the process as possible.
It is better to have one connection left open for a longer duration than to open and close multiple connections.
If your code is performance-sensitive, then the preferred technique tends to be to use some form of connection pooling and/or persistent processes so that you can open one database connection and then use that connection to service many page requests rather than opening a new connection for each request that needs one.
If your code is not performance-sensitive, then it doesn't really matter anyhow.
Either way, the exact timing of when the database is accessed in the course of handling a specific request isn't that great of a cause for concern.
My personal practice is to open a database connection immediately when a new handler process is spawned, then verify that it's still alive when I start processing each request. The rest of the code is then free to just assume that the connection is available when needed without incurring the cost of connecting while a user is waiting for a response.

What are the security implications of not closing connection to the database after you are done with it?

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?
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.
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.
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.
Jeff Atwood wrote an interesting blog post on this very subject that you might find interesting.

Categories