mowwwalker
mowwwalker

Reputation: 17334

PHP viewing a file as hex?

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);

   } 

} 

Upvotes: 2

Views: 6370

Answers (2)

user187291
user187291

Reputation: 53940

I don't understand how your class works, but to convert to hex you can use

$hex = unpack("H*", file_get_contents($filename));
$hex = current($hex);

and to convert a hexdump back to source:

$chars = pack("H*", $hex);

Upvotes: 7

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.

Upvotes: 1

Related Questions