Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long does a PHP MySQL database connection remain active?

I have a long running PHP script. I am making the database connection at the very beginning of the script and does some database operation at the start up.

After that, the script perform 4 hours of PHP operation without pinging to MySQL with that connection even a single time.

At the end of these long running PHP operations, when I try to execute mysql_query it gives me the following error: MySQL Server has gone Away

Is there any possibility of increasing the connection timeout to be 4 hours? I am using PHP ADODB to connect with MySQL from my PHP application.

Please suggest what to do?

like image 556
Maulik Vora Avatar asked Feb 24 '12 06:02

Maulik Vora


People also ask

How long does MySQL connection stay open?

By default, the server closes the connection after eight hours if nothing has happened. You can change the time limit by setting the wait_timeout variable when you start mysqld. See Section 5.1. 8, “Server System Variables”.

Does PHP automatically close MySQL connection?

Most CMSs close the MySQL connection at the end of the request, which is really meaningless, because PHP will do it anyway.

Does PHP use persistent connection?

Persistent Database Connections ¶ Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it.

What happens if you dont close database connection PHP?

If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persistent connections).


1 Answers

MySQL has a different timeout than PHP. You could increase it in php.ini on the line mysql.connect_timeout = 14400. Also increase the default_socket_timeout = 14400

Note that if your PHP setting allow you to do an ini_set, you can also do as follows:

ini_set('mysql.connect_timeout', 14400);
ini_set('default_socket_timeout', 14400);
like image 76
Osh Mansor Avatar answered Nov 01 '22 22:11

Osh Mansor