I had looked for a way to view a file as hex a while ago and found:
class Hex
{
var $file;
var $hex;
function __construct($file)
{
$this->file = $file;
}
function gethex()
{
$handle = fopen($this->file, 'r') or die('Permission?');
while(!feof($handle))
{
foreach(unpack('C*',fgets($handle)) as $dec)
{
$tmp = dechex($dec);
$this->hex[] .= strtoupper(str_repeat('0',2-strlen($tmp)).$tmp);
}
}
return join($this->hex);
}
function writehex($hexcode)
{
foreach(str_split($hexcode,2) as $hex)
{
$tmp .= pack('C*', hexdec($hex));
}
$handle = fopen($this->file, 'w+') or die('Permission?');
fwrite($handle, $tmp);
}
}
It worked great for one file, but I think I’m running into problems with trying to do it with multiple files. Is there anything wrong with the script? Should it close the files somewhere? Should I delete the instances of it after using them?
Would this be better?:
class Hex
{
var $file;
var $hex;
function __construct($file)
{
$this->file = $file;
}
function gethex()
{
$handle = fopen($this->file, 'r') or die('Permission?');
while(!feof($handle))
{
foreach(unpack('C*',fgets($handle)) as $dec)
{
$tmp = dechex($dec);
$this->hex[] .= strtoupper(str_repeat('0',2-strlen($tmp)).$tmp);
}
}
fclose($handle);
return join($this->hex);
}
function writehex($hexcode)
{
foreach(str_split($hexcode,2) as $hex)
{
$tmp .= pack('C*', hexdec($hex));
}
$handle = fopen($this->file, 'w+') or die('Permission?');
fwrite($handle, $tmp);
fclose($handle);
}
}
I don’t see problems with multiple files with this script but it could become a problem when you do not close the file. Best would be to close the file before the end of the function/the return.