There are only 2 ways a connection won't get closed.
A. If you have persistent connections turned on (even then it will only have 1 connection per apache process)
B. If there is some other deeper issue going on with php or mysql.
When a PHP script finishes, everything closes along with it. There is nothing you actually need to do to actually close the connection.
What you probably should do is once it's been running for awhile, go into your control panel and then run the following SQL command:
That will show you any processes (connections) that are currently open. That should give you an idea if there are lingering connections hanging around.
You should definitely run that query when you're getting the max_connections error and let us know what you find.