views:

318

answers:

2

I am connecting to a remote website via sockets. I am expecting a specific string 'XXX' from the remote site. Upon receipt of the string, I want to send back an 'ACK' 200 OK response back to the remote server.

This is what I have so far (assume socket successfully opened); $fp is resource (pointer) to the socket:

 while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) {
 // Send 200 OK 'ack' response to remote server
     $response = "HTTP/1.0 200 OK\r\n";
 fputs ($fp, $response);

     // Do additional processing here ...
   }
 }
 fclose($fp)

What I am not sure about, is whether it is 'legal' to use fputs in the (!feof()) while loop. If there is anything wrong with the above code, I will be grateful if someone could point it out (i.e. if it could be written better).

+2  A: 

This looks fine, but if all you're looking for is one string you may as well break out of the read loop as soon as you've found it.

e.g.

while (!feof($fp)) {
   $data = fgets ($fp, 1024);
   if (strcmp("PASS",$data)==0) 
      break;
 }

$response = "HTTP/1.0 200 OK\r\n";
fputs ($fp, $response);

fclose($fp);
Chris Newman
+1  A: 

If your "additional processing" in the loop means you'll be reading more from the socket handle, then I would say you have to finish reading in all of its response before you send something back.

How about setting a status in that loop to indicate you're going to send back the 200 when you're finished processing that server's response to you. Then after you're all done with the loop, fputs back the response.

Oh, the previous answer says about the same thing except you might not want to be breaking the loop just because you found "PASS".

grantwparks