Skip to content
Advertisement

How do i send a byte stream to a socket with PHP?

In GO i can do the following:

conn, _ := net.Dial("tcp", CONNECT) // Client

request := []byte{01, 00} // The request start with 0100

request = append(request, []byte(`09302020073014323720200730007402`)...) // The request

conn.Write(request)

This does work, however, i’m unable to translate this to PHP.

What i have so far:

$fp = stream_socket_client("tcp://x:x", $errno, $errstr, 5);
  if (!$fp) {
      echo "$errstr ($errno)<br />n";
  } else {
      $queryString = '010009302020073014323720200730007402';
    
      fwrite($fp, $queryString);
      echo fgets($fp, $responseSize);
      fclose($fp);
  }
    

I tried using the described solutions here with no success, the server does not recognise my input.

Advertisement

Answer

In your Go example, your request begins with the bytes 0x01, and 0x00. In PHP, you’re writing the byte encoding of the string '0100'. These aren’t exactly the same, and you can view how they differ here: https://play.golang.org/p/0gidDZe4lZF

What you really want to be writing is the single byte 0x0, and 0x1 at the beginning of your string instead of these characters.

Using PHP’s builtin chr function we can create a string using the single bytes 0x0 and 0x1 like so:

$queryString = chr(0) . chr(1);
$queryString .= '09302020073014323720200730007402'

Barring any additional encoding issues on the PHP side of things, that should match your query in your Go example.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement