PHP Sockets: Keeping sockets open..?

In a PHP script that uses PHP sockets, if you call socket_create yet forget to (or intentionally do not) call socket_close(), does the socket automatically close itself at the end of the scripts’ execution or does it remain open even after the script finishes and dies?

I actually want to intentionally keep a socket open; I’m writing a frontend server script that responds to AJAX calls, it uses a certain port to query a backend server application bound to another port. Since I most likely will be receiving multiple calls from multiple users, I wonder if and how I could have multiple instances of the frontend script using the same port, and if/how I could keep a port opened for these multiple instances. Obviously I can’t have each instance calling socket_create on the same port.

I can’t find it in any of the official documentation, but my best guess is that the socket connection is closed after the script is ended.

However, that doesn’t seem to be your issue. You’re forgetting that socket connections are not maintained at the port they’re opened (at least, not unless you rewrote your OS’ socket foundations to specifically do so). What happens:

  • initiate socket
  • connect to the specified port
  • responce from server -> different (random) port is returned
  • socket connection is made on the random port
  • specified port is freed for the next socket request

Correct me if I’m wrong. It’s best to just provide a graceful shutdown/closure procedure in your script. Open a connection when you need to in your script, then close it again when you’re done with it. AJAX calls are calls to separate scripts btw, and those scripts will re-initiate the socket connection, withdraw updated data, and then close the connection again.

That helped a lot. Thanks! :)

Sponsor our Newsletter | Privacy Policy | Terms of Service