title: Proper and fast way to TELNET in PHP. Sockets or cURL
body: <p>Almost all examples of the TELNET implementations in PHP are with sockets (<em>fsockopen</em>). This does not work for me, because it takes an unacceptable amount of time (~ 60 seconds).</p>
  
  <p>I have tried <em>fsockopen</em> for other purposes and found it slow in contrast to cURL.</p>
  
  <p><strong>Question #1:</strong> Why are sockets that slow?</p>
  
  <p><strong>Update:</strong> I found we need to set <a href="http://www.php.net/manual/en/function.stream-set-timeout.php" rel="nofollow noreferrer">stream_set_timeout</a> function, and we can control the socket execution time. I'm curious how to set the proper timeout or how to make it "stop waiting" once the response is received.</p>
  
  <hr>
  
  <p>I can't get the same thing implemented with cURL. Where should I put the commands which I need to send to telnet? Is <em>CURLOPT_CUSTOMREQUEST</em> the proper option?  I'm doing something like this:</p>
  
  <pre><code>class TELNETcURL{
  
      public $errno;
      public $errstr;
      private $curl_handle;
      private $curl_options = array(
          CURLOPT_URL =&gt; "telnet://XXX.XXX.XXX.XXX:&lt;port&gt;",
          CURLOPT_TIMEOUT =&gt; 40,
          CURLOPT_RETURNTRANSFER =&gt; TRUE,
          CURLOPT_HEADER =&gt; FALSE,
          CURLOPT_PROTOCOLS =&gt; CURLPROTO_TELNET
      );
  
      function __construct(){
          $this-&gt;curl_handle = curl_init();
          curl_setopt_array($this-&gt;curl_handle, $this-&gt;curl_options);
      }
  
      public function exec_cmd($query) {
          curl_setopt($this-&gt;curl_handle, CURLOPT_CUSTOMREQUEST, $query."\r\n");
          $output = curl_exec($this-&gt;curl_handle);
          return $output;
      }
  
      function __destruct(){
          curl_close($this-&gt;curl_handle);
      }
  
  }
  </code></pre>
  
  <p>And then something similar to this:</p>
  
  <pre><code>$telnet = new TELNETcURL();
  print_r($telnet-&gt;exec_cmd("&lt;TELNET commands go here&gt;"));    
  </code></pre>
  
  <p>I am getting "Max execution time exceeded 30 seconds" on curl_exec command.</p>
  
  <p><strong>Question #2:</strong> What is wrong with the cURL implementation?</p>