In short, given the code you've shown, you can't. Every time the php script terminates it will close the socket.
The only way you can do it is to keep the script cycling in a loop. Open the socket before the loop and then inside the loop, keep checking a database table for new commands etc that you want to send via the connection. When the script is ready to close the connection you can break out of the loop and then close it.
As for the GUI, you'd need another page which you can input your commands on, submit and they are put into the database for the socket script to pick up. If you wanted to really pimp it up you could use ajax so that you don't have to keep refreshing the page.
Note that you could actually just use the session instead of the DB but with the DB at least you'd have a log of everything.
My helpful sig is on vacation trying to loose some weight. It got a bit fat and caused a few problems but it will be back at some point!