Rob
Rob

Reputation: 8101

fwrite() not writing. Error with my code, or the remote client?

Trying to set up a script to send commands to a remote client on a Win32 system. Here is the code:

$command = $_POST['command'];
$host = $_POST['host'];
$port = $_POST['port'];
$fp = @fsockopen($host, $port, $e, $s, 15);
if (!$fp) {
    echo 'Error! Here\'s your problem: ' . $e . ': ' . $s;
}else{
    $fw = fwrite($fp, $command);
        if (!$fw){
            echo 'Failed sending command.';
            fclose($fp);
        }else{
            fclose($fp);
            echo 'Successfully sent: ' . $command;
        }
}

My buddy is working on the remote client, and he says that this script is sending ''

However, my script is echoing Successfully sent: test

Am I doing something wrong, or is it a problem on his end?

Upvotes: 0

Views: 1181

Answers (2)

VolkerK
VolkerK

Reputation: 96159

(Not a solution ...yet)
What does

$command = $_POST['command'];
$host = $_POST['host'];
$port = $_POST['port'];

$fp = @fsockopen($host, $port, $e, $s, 15);
if (!$fp) {
  echo 'Error! Here\'s your problem: ' . $e . ': ' . $s;
}
else{
  $fw = fwrite($fp, $command);

  if (false===$fw) {
    echo 'Failed sending command. ';
    if ( function_exists('error_get_last') ) {
      var_dump( error_get_last() );
    }
  }
  else if ( strlen($command)!==$fw ) {
    printf('only %d of strlen(%s)=%d bytes have been sent', $fw, $command, strlen($command));
  }
  else{
    echo 'Successfully sent ', $fw, ' bytes. command=', $command;
  }
  fclose($fp);
}

print?

update: Does it work when you test it against this dummy server script (via php-cli)?

$srv = socket_create_listen(8082);

for($dbgCounter=0; $dbgCounter < 60; $dbgCounter++ ) {
  echo '.';
  $read = array($srv); $write=array(); $ex=array();
  if ( 0 < socket_select($read,  $write, $ex, 1) ) {
    echo "\n";
    $c = socket_accept($srv);
    echo "socket accepted\n";
    while( 0<socket_recv($c, $buffer, 1024, 0) ) {
      var_dump($buffer);
    }
    echo "socket_close\n";
    socket_close($c);
    $dbgCounter = PHP_INT_MAX;
  }
}
echo "done.\n";

First try it on the same machine ($_POST['host']==='localhost') then on the remote machine (if there is such a thing).

Upvotes: 2

wimvds
wimvds

Reputation: 12850

Are you testing it with UDP connections? It is possible that opening the socket fails silently when using UDP (ie. because of firewall rules or anti-virus/malware software), and you'll only notice this when you try to write data to it (see the warning regarding UDP on http://php.net/manual/en/function.fsockopen.php). Adding error_reporting(E_ALL); might help to find the actual cause.

Upvotes: -1

Related Questions