0

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
  • This is shorter, (untested): if (strpos(file_get_contents('php://input'), 'PASS') !== false) { header("HTTP/1.0 200 OK\r\n"); } Commented Oct 21, 2009 at 15:26
  • 1
    Just out of curiosity: Why does your script (seemingly the client) "send a HTTP/1.0 200 OK\r\n" to what seems to be the http server? Commented Oct 21, 2009 at 16:19

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.