1

I use the script below to connect to an external PBX server and get the call logs.

However it only returns 1 sting at a time which equals 1 log. So I need to refresh multiple times to get all the available logs.

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die();
$result = socket_connect($socket, $address, $port) or die();

$out = socket_read($socket, 2048);

How do I get all the strings available without having to reinitiate the connection all the time?

Nikk
  • 7,384
  • 8
  • 44
  • 90

1 Answers1

1

Probably you mean reading from socket in cycle? According to documentation (http://php.net/socket_read) you can do something like that while ($portion = socket_read($socket, 2048)) { do_something_with_that_portion_of_log; } and if data exhausted you got empty string or FALSE if error occurred.

FINAL SOLUTION

We use socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=> 10, 'usec'=> 0)); with default non-blocking mode. After all logs will be read program will be wait for ~10 secs and finishing.

https://gist.github.com/mihalicyn/533273e0d8b23de33aaf7f2cf0973d88

  • It doesn't work. The page just keeps loading endlessly. What could be causing it to do this? I want to loop through all the records and get them all. Every time I call socket I get 1 string in return. – Nikk Aug 11 '17 at 15:05
  • You can use `socket_set_nonblock($socket);` to set non-blocking mode on read operation. This is php documentation issue. :( – Alexander Mihalicyn Aug 11 '17 at 15:11
  • When I try to `var_dump($portion);` I now get `bool(false)`. Any clue what that is about? – Nikk Aug 11 '17 at 15:13
  • You can use socket_last_error function (http://php.net/manual/ru/function.socket-last-error.php) to get error code and socket_strerror to it's string representation. ;) Probably you got SOCKET_EWOULDBLOCK when data in socket is exhausted. – Alexander Mihalicyn Aug 11 '17 at 15:15
  • I get: `Couldn't create socket: [11] Resource temporarily unavailable` – Nikk Aug 11 '17 at 15:19
  • This is what I have: `$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die();` `$result = socket_connect($socket, $address, $port) or die();` `$result = socket_set_nonblock($socket);` `$portion = socket_read($socket, 2048);` Plus the socket error stuff below this. – Nikk Aug 11 '17 at 15:19
  • set non-blocking mode before socket_connect call – Alexander Mihalicyn Aug 11 '17 at 15:23
  • It now is before `socket_connect`. And I get a blank screen. Nothing gets echoed in the script nor anything gets processed. – Nikk Aug 11 '17 at 15:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/151735/discussion-between-alexander-mihalicyn-and-borsn). – Alexander Mihalicyn Aug 11 '17 at 15:29
  • I checked the logs. It doesn't log any errors when it's a blank screen. – Nikk Aug 11 '17 at 16:14