Search code examples
phpsocketscurltelnet

Proper and fast way to TELNET in PHP. Sockets or cURL


Almost all examples of the TELNET implementations in PHP are with sockets (fsockopen). This does not work for me, because it takes an unacceptable amount of time (~ 60 seconds).

I have tried fsockopen for other purposes and found it slow in contrast to cURL.

Question #1: Why are sockets that slow?

Update: I found we need to set stream_set_timeout 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.


I can't get the same thing implemented with cURL. Where should I put the commands which I need to send to telnet? Is CURLOPT_CUSTOMREQUEST the proper option? I'm doing something like this:

class TELNETcURL{

    public $errno;
    public $errstr;
    private $curl_handle;
    private $curl_options = array(
        CURLOPT_URL => "telnet://XXX.XXX.XXX.XXX:<port>",
        CURLOPT_TIMEOUT => 40,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HEADER => FALSE,
        CURLOPT_PROTOCOLS => CURLPROTO_TELNET
    );

    function __construct(){
        $this->curl_handle = curl_init();
        curl_setopt_array($this->curl_handle, $this->curl_options);
    }

    public function exec_cmd($query) {
        curl_setopt($this->curl_handle, CURLOPT_CUSTOMREQUEST, $query."\r\n");
        $output = curl_exec($this->curl_handle);
        return $output;
    }

    function __destruct(){
        curl_close($this->curl_handle);
    }

}

And then something similar to this:

$telnet = new TELNETcURL();
print_r($telnet->exec_cmd("<TELNET commands go here>"));    

I am getting "Max execution time exceeded 30 seconds" on curl_exec command.

Question #2: What is wrong with the cURL implementation?


Solution

  • sockets are not slow. sockets are the base for communication. Curl uses sockets to open a connection to the remote server. Everything works on sockets (i think). I don't think you can use curl to use a telnet service, well, that's not entirely true, i guess you can connect and send a single command. Curl was designed with http protocol in mind which is stateless (you open a connection, send a request, wait a reply and the close the connection). Sockets are the only option.

    I am getting "Max execution time exceeded 30 seconds" on curl_exec command.

    My guess is that the remote server is the culprit. check to see if it works using a regular terminal client, or increase the max_execution_time in php ini.

    UPDATE

    It seems it is possible to use curl for telnet, check this: http://www.cs.sunysb.edu/documentation/curl/

    But i still think you are better off using sockets.