1

I've looked in to this a bit but still don't really understand if its possible.

I have a small webserver that sits on my private network. I want to create a php script that will connect to a telnet server on the private network and send it text every 30 seconds.

Obviously the easy part is the text and timing but connection to a TCP Port 23 and sending a string of text seems harder for some reason. What's the best way to do this?

ahackney
  • 534
  • 6
  • 14
  • The php manual has an [example](http://php.net/manual/en/sockets.examples.php) for socket . – frz3993 Apr 18 '17 at 15:09
  • And I tried it. I can connect and it shows the connection but I can't seem to send a string of text to the device. – ahackney Apr 19 '17 at 16:16

1 Answers1

5

Use PHP sockets :

<?php
while(true){
    sleep 30;
    $fp = fsockopen("www.example.com", 23, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    } else {
        fwrite($fp, "The string you want to send");
        while (fgets($fp, 128)) {
            echo fgets($fp, 128); // If you expect an answer
        }
        fclose($fp); // To close the connection
    }
}
?>
Reda Maachi
  • 853
  • 6
  • 15
  • [why `while (!feof($fp))` is wrong](http://stackoverflow.com/questions/34425804/php-while-loop-feof-isnt-outputting-showing-everything) – Barmar Apr 18 '17 at 15:20
  • That means until the end of file :) – Reda Maachi Apr 19 '17 at 07:22
  • 1
    That's what you would think, but it's wrong. It does an extra `fgets()` after the end of file. Read the linked question. You should use `while (fgets($fp, 128))` – Barmar Apr 19 '17 at 15:37
  • 1
    I think the `while (fgets($fp, 128))` edit is wrong. The while will read data then the echo will read more data, not the same data again. You should be reading into a buffer and echoing that, borrowing from the linked question... `while (($buffer = fgets($fp, 128)) !== false) { echo $buffer; }` – PeteWiFi Nov 13 '18 at 08:57