1

I am trying to send a .BIN file over a TCP socket using PHP. This is what I have:

$fp = fsockopen("127.0.0.1", 80, $errno, $errstr, 30);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "You message");
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

I am unsure how to send the BIN file, and when testing it, the page just infinitely loops.

Can someone help me? Is there a better way to send a file over TCP using PHP?

3
  • You have one file resource open (the socket to write to) but your loops looks like you're reading from another (presumably the bin file). Open the bin file using fopen() and in the loop fwrite the contents out to the socket. Commented Aug 27, 2017 at 22:29
  • @RichGoldMD I am trying to understand what you mean. Do you have a coding example for me so I can fully understand what you are trying to point out? Commented Aug 27, 2017 at 22:33
  • See my answer below Commented Aug 27, 2017 at 22:35

1 Answer 1

1

You need 2 file resources, but you are only opening the outbound one:

$fp = fsockopen("127.0.0.1", 80, $errno, $errstr, 30);
$fb_bin = fopen("myfile.bin", 'rb'); 
// TODO error test $fp_bin

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    // fwrite($fp, "You message");
    while (!feof($fp_bin)) {
        fwrite($fp, fread($fp_bin, 128)); // ? use a larger value
        // TODO Error test the read and write operations
    }
    fclose($fp);
    fclose($fp_bin);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I will give this a try and see if I can debug this further, and of course let you know.
Have you had any luck?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.