1

I have some a java server that I'm trying to get to play with a php script.

The format provides the number of bytes the message will take as an unsigned byte, and then the bytes that comprise the string.

here's my function with commentary

function read($socket, $readnum) {
    $endl = "<br>"; // It's running on apache

    // attempt to get the byte for the size
    $len = unpack("C",socket_read($socket, 1))[0];
    // this prints "after ", but $len does not print. $endl does
    echo "after " . $len . $endl;
    // obviously this fails because $len isn't in a valid state
    $msg = socket_read($socket, $len);
    // print the message for debugging?
    echo $len . " " . $msg;
    return $msg;
}

I'm not really a php guy, more of a Java guy, so I'm not sure how I should go about getting this length.

On @c0le2's request, I made the following edit

$lenarr = unpack("C",socket_read($socket, 1));
$len = $lenarr[0]; // line 81

Which gave the following error

PHP Notice:  Undefined offset: 0 in simple_connect.php on line 81
corsiKa
  • 81,495
  • 25
  • 153
  • 204

2 Answers2

3

The unpack format string is actually like code [repeater] [name], separated by forward slashes. For example, Clength. The output array will be associative and keyed by name, with repeated fields having a numeric suffix appended, starting at 1. E.g. the output keys for C2length will be length1 and length2.

The documentation is not super-clear about this.

So when you don't specify any name, it just appends the numeric suffix, starting at 1. So the length you are looking for is $lenarr[1].

But you should try this instead:

$v = unpack('Clength', "\x04");
var_export($v);  // array('length' => 4)

Here are some other examples:

unpack('C2length', "\x04\x03");
// array ( 'length1' => 4, 'length2' => 3, );

unpack('Clength/Cwidth', "\x04\x03");
// array ( 'length' => 4, 'width' => 3, );

Also, in php you can't generally use array-access notation on an expression--you need to use it on the variable directly. So functioncall()[0] won't work, you need $v = functioncall(); $v[0]. This is a php wart.

Francis Avila
  • 31,233
  • 6
  • 58
  • 96
0

You can't access a returned array like that. You'd do $len[0] after calling unpack().

$len = unpack("C",socket_read($socket, 1));    
echo "after " . $len[0] . $endl;
cOle2
  • 4,725
  • 1
  • 24
  • 26
  • That gives me "Undefined offset: 0 in simple_connect.php on line 81". I'll make an edit that shows my exact code. It occurs on the $len assignment. – corsiKa May 07 '12 at 18:40
  • @corsiKa: Do a `print_r($len);`, it will show what the key is (maybe it's [1] instead). – cOle2 May 07 '12 at 18:41