-2

I am trying to make a persistent connection to a weburl and read the response from the url every moment (Connection will not be disconnected).

Looking for something like this.

connection = connect("http://www.ibm.com?id=test"); while(connection has response){ //do something with the response until the connection in forcefully closed }

I had a look into pecl_http library. But this will not serve the purpose. Can we use curl to make a persistent connection to a web url?

Or is it something which is not supported in php?

Resna
  • 1
  • How about `fopen()`? – Cobra_Fast Apr 11 '18 at 15:12
  • 4
    Will the remote server keep streaming an endless HTTP response body…? HTTP doesn't seem like the best protocol for this, rather a web socket would be for streaming data. – deceze Apr 11 '18 at 15:12
  • 1
    Persistent connection doesn't mean `"hey, something changed, here's the content"`. How well do you understand HTTP protocol? – N.B. Apr 11 '18 at 15:22
  • @deceze The API has a web socket and it stream data using https protocol. How do I go about it then? Create a web socket in my php application and then connect to the url? – Resna Apr 11 '18 at 16:48
  • So you really want to create a *web socket* connection, yes? – deceze Apr 11 '18 at 18:28

2 Answers2

0

Look how http protocol works. It's not possible to have persistent connection and receive event when content is changed. You can use websockets or long-polling. Check this library found on github https://github.com/panique/php-long-polling

stalwart
  • 78
  • 8
  • It's certainly *possible*, it's just a bad use of HTTP and not very typical… – deceze Apr 11 '18 at 15:29
  • what the f are you smoking? it's fully possible to keep pushing data to a single http connection indefinitely. it's not gonna be easy if you're pushing to a web browser tho, cus of the caching n stuff the web browser is doing. but with something like curl, it's no problem. – hanshenrik Apr 12 '18 at 09:08
0

use the socket api.

$sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_connect($sock,"www.ibm.com",80);
$data=implode("\r\n",array(
'GET /?id=test HTTP/1.0',
'Host: www.ibm.com',
'User-Agent: PHP/'.PHP_VERSION,
'Accept: */*'
))."\r\n\r\n";
socket_write($sock,$data);
while(false!==($read_last=socket_read($sock,1))){
   // do whatever
    echo $read_last;
}
var_dump("socket_read returned false, probably means the connection was closed.",
"socket_last_error: ",
socket_last_error($sock),
"socket_strerror: ",
socket_strerror(socket_last_error($sock))
);
socket_close($sock);
hanshenrik
  • 19,904
  • 4
  • 43
  • 89