[PHP] Outputting raw binary

Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
Is there an easy way of doing this? I'm trying to make a small PHP page that contains data to be read by a program (pulled from a database on the server), so I don't want it to be displayed as text.
 
Thanks, but I actually wanted a way of outputting data without it being encoded to a string at all by PHP.

For example, say I want to output the number 14345 as a 32-bit integer, I want to send the number literally as a number, not as a string containing the number. The way PHP would send it is by encoding it to a string, and then sending that string's binary:
31 34 33 34 35 (shown in hex, one byte/character at a time)

What I want to be sent instead of this, is the number itself, which would be this:
09 38 00 00 (shown as hex, with little-endian byte order)

The problem is, PHP always sends output as a string, and I don't know any way of stopping it from doing that :confused:
 
Dj_Jestar said:
streams, or readfile()
Using streams is overkill really what what I'm doing, and readfile() would work, but I need to be able to generate content on the fly, so messing around with files isn't ideal.

I've actually just written my own (very crude) class to write binary data:
Code:
<?php

class BinaryWriter
{
	private $dataString = '';

	public function writeInt32($number)
	{
		$intValue = intval($number);
		for ($i = 0; $i < 4; $i++)
		{
			$byteValue = ($intValue >> ($i * 0x10)) & 0xFF;
			$this->dataString .= chr($byteValue);
		}
	}

	public function writeInt16($number)
	{
		$intValue = intval($number);
		for ($i = 0; $i < 2; $i++)
		{
			$byteValue = ($intValue >> ($i * 0x10)) & 0xFF;
			$this->dataString .= chr($byteValue);
		}
	}

	public function writeByte($number)
	{
		$intValue = intval($number);
		$this->dataString .= chr($intValue);
	}

	public function writeBString($string)
	{
		$length = strlen($string);
		$this->dataString .= chr($length);
		$this->dataString .= $string;
	}

	public function writeZString($string)
	{
		$this->dataString .= $string;
		$this->dataString .= chr(0);
	}

	public function flush()
	{
		header('Content-type: application/octet-stream');
		echo $this->dataString;
		$this->dataString = '';
	}
}

?>
It's rather lacking in terms of functionality, and isn't exactly elegant, but it does the job :D
 
Last edited:
Back
Top Bottom