hexdump.inc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * View any string as a hexdump.
  4. *
  5. * This is most commonly used to view binary data from streams
  6. * or sockets while debugging, but can be used to view any string
  7. * with non-viewable characters.
  8. *
  9. * @version 1.3.2
  10. * @author Aidan Lister <aidan@php.net>
  11. * @author Peter Waller <iridum@php.net>
  12. * @link http://aidanlister.com/repos/v/function.hexdump.php
  13. * @param string $data The string to be dumped
  14. * @param bool $htmloutput Set to false for non-HTML output
  15. * @param bool $uppercase Set to true for uppercase hex
  16. * @param bool $return Set to true to return the dump
  17. */
  18. function hexdump ($data, $htmloutput = true, $uppercase = false, $return = false)
  19. {
  20. // Init
  21. $hexi = '';
  22. $ascii = '';
  23. $dump = ($htmloutput === true) ? '<pre>' : '';
  24. $offset = 0;
  25. $len = strlen($data);
  26. // Upper or lower case hexidecimal
  27. $x = ($uppercase === false) ? 'x' : 'X';
  28. // Iterate string
  29. for ($i = $j = 0; $i < $len; $i++)
  30. {
  31. // Convert to hexidecimal
  32. $hexi .= sprintf("%02$x ", ord($data[$i]));
  33. // Replace non-viewable bytes with '.'
  34. if (ord($data[$i]) >= 32) {
  35. $ascii .= ($htmloutput === true) ?
  36. htmlentities($data[$i]) :
  37. $data[$i];
  38. } else {
  39. $ascii .= '.';
  40. }
  41. // Add extra column spacing
  42. if ($j === 7) {
  43. $hexi .= ' ';
  44. $ascii .= ' ';
  45. }
  46. // Add row
  47. if (++$j === 16 || $i === $len - 1) {
  48. // Join the hexi / ascii output
  49. $dump .= sprintf("%04$x %-49s %s", $offset, $hexi, $ascii);
  50. // Reset vars
  51. $hexi = $ascii = '';
  52. $offset += 16;
  53. $j = 0;
  54. // Add newline
  55. if ($i !== $len - 1) {
  56. $dump .= "\n";
  57. }
  58. }
  59. }
  60. // Finish dump
  61. $dump .= $htmloutput === true ?
  62. '</pre>' :
  63. '';
  64. $dump .= "\n";
  65. // Output method
  66. if ($return === false) {
  67. echo $dump;
  68. } else {
  69. return $dump;
  70. }
  71. }
  72. ?>