How to make a server application with PHP

I need to write some service for my application. I want each client to have limited persistent connections (for example, only the first 10 clients can connect).

I know that I can listen to a port using PHP socket_listen() . The parent process accepts the connection, then the pcntl_fork() process has children to handle the connection.

But as far as I know, PHP resources are not saved when fork () ed. I wonder if this can be done with PHP, or should I do it in C?

+4
source share
2 answers

1) Why bother? Run the daemon as one process and use socket_select () (or stream_select) to listen for requests.

See the code of Alexey Zapparov here for a ready-made solution.

2) Why worry about the pain in writing your own socket code - use [x] inetd to manage the servers and do all communications on stdio (note that unlike solution 1 there will be a separate process for each client - therefore, the processing code will be non-blocking)

- You correctly say that PHP resources should not be available in a forked process, but not indicate how this relates to your current problem. Is it just that you can count the number of connections? Or something different? In the case of the first, there is a much simpler way to do this. Using solution 1, simply increase and decrease the counter variable when connecting / disconnecting clients. In case 2, the same approach, but save the variable in the data file / database (you can also store connection information and run checks periodically). Alternatively restrict connections on the firewall.

FROM.

+1
source

Perhaps you could try sharing it with memcache ( http://www.php.net/manual/en/book.memcache.php ). (I never tried this, can it work)

0
source

Source: https://habr.com/ru/post/1309959/


All Articles