62

Looking for a way to produce a filename-safe hash of a given PHP array. I'm currently doing:

$filename = md5(print_r($someArray, true));

... but it feels "hacky" using print_r() to generate a string unique to each array.

Any bright ideas for a cleaner way to do this?

EDIT Well, seems everyone thinks serialize is better suited to the task. Any reason why? I'm not worried about ever retrieving information about the variable after it's hashed (which is good, since it's a one-way hash!). Thanks for the replies!

loneboat
  • 2,845
  • 5
  • 28
  • 40
  • 2
    I think this is a pretty decent way of doing it, actually. – Dutchie432 Feb 23 '11 at 21:54
  • I would say it is equally effective both ways. However, considering the difference between them in their purpose, it seems more correct as a matter of principle to use serialize instead of print_r. But that's only if you have programmer OCD like me. :) – OCDev Sep 27 '16 at 09:51
  • `sha1` seems more unique. `$sign = sha1(json_encode($data));` – Hebe Dec 04 '20 at 20:24

5 Answers5

104

Use md5(serialize()) instead of print_r().

print_r()'s purpose is primarily as a debugging function and is formatted for plain text display, whereas serialize() encodes an array or object representation as a compact text string for persistance in database or session storage (or any other persistance mechanism).

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
25

Alternatively you could use json_encode

generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • 2
    Using json_encode to provide a hashing seed is not safe. For example, if the array you are using with json_encode has a non UTF-8 character, json_encode will return false, this will make all your md5 hashes the same. – Amir Iskander Jan 30 '19 at 12:32
14

serialize() should work fine.

It has the additional advantage of invoking the __sleep magic method on objects, and being the cleanest serialization method available in PHP overall.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • I love how this is the first answer posted, and yet gotten right from the first go, without even one edit over all these years – ᴍᴇʜᴏᴠ Apr 18 '19 at 07:59
10

What about serialize?

$filename = md5(serialize($someArray));

Damp
  • 3,328
  • 20
  • 19
3

Using serialize() might be more conservative if you want to keep the type, etc...

greg0ire
  • 22,714
  • 16
  • 72
  • 101