PHP Socket Client - Issue with while (!feof($fp)) loop


I'm writing a PHP script to communicate with an application through TCP/IP.

I'm sending queries to the application and I need to read the data the server sends back.

My problem is with the while(end of file) loop. The script freezes when I'm using it. It works with a simple For loop but I need a dynamic loop as the numbers of records to return will vary with time.

Here is an exemple of the server response

--After Connection:
Avantage - Intýgration 16.6,Server 4.3,067738

--After login

--After query

I need to parse all the data after the query in an array so I can use those value to populate a drop down list in a form.

Any ideas on how to fix the loop?
        //Create the socket connection
        $fp = fsockopen('XXXX.XXXX.XXXX.XXXX', 2131, $errno, $errstr);
        //LOGIN query
	$message = "LOGIN,10,OPERATEUR,****\n";
	//Data query
	$message2 = "RQ01,R01,,CNT,CONUM,,/COINACTIF==\"F\",CONUM\n";
        if (!$fp) 
            echo "$errstr ($errno)<br />\n";
            // get the welcome message 
            $line1 = fgets($fp, 1024);
            echo 'got first line:  '.$line1;
            // write the login query to the socket
            fwrite($fp, $message, strlen($message)) or die('Error sending the input string.');
            echo '<br/>sent msg:        '.$message;
            // get the result
            $result .= fgets($fp, 1024);
            echo "<br/>got response: $result\n";
	    // write the data query to the socket
            fwrite($fp, $message2, strlen($message2)) or die('Error sending the input string.');
            echo '<br/>sent msg:        '.$message2;
			// read all records returned by the server - SCRIPT FREEZES HERE
			$projectNo = array();
			$cpt = 0;
			while (!feof($fp)) 
				$projectNo[$cpt] = fgets($fp, 1024);
				echo $Array[$i]; 
       //close the connection
        echo 'closing connection'."\n";
        echo 'connection closed';

Open in new window

Who is Participating?
EnDscxConnect With a Mentor Author Commented:
Well I solved my own problem using the code below.

By putting every record in a string variable in the loop and checking if that string contains the word "END" everytime it loops the script will exit the loop when the server sends the line containing END which means it sent all the records (which it always do after every query).
    $noProjet = fgets($fp, 1024);
    $projectNo[$cpt] = $noProjet;
while(substr_count($noProjet,"END") != 1);
//Looping through the array I can see all the records I needed
//Easy to put those in a drop down list now :)
    echo $projectNo[$i]; 
    echo "<br/>";			

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.