tags:

views:

55

answers:

2

PHP appears to be giving different hash values when I use php -r <code> on the command line and when I execute the file with php <file>, php -f <file>, or run the code inside Apache.

For instance, a SHA1 usage on command line using -r:

$ php -r "print sha1('$1S*90');"
77cd8b48ceca53e018f80536b0a44c5b6710425f

When I try the same with file testSHA.php below:

<?php
print sha1('$1S*90');
?>

and run it on command line or inside Apache using mod_php5:

$ php testSHA.php
201cb5aaa7d4db1a49d9be1f2c06d45e4c2a69f2

Strangely, though, the hashes do match using the two methods when I try a different input string such as "123456789".

I don't think I am using a different encoding or character set in the two methods. I also tried using MD5 and still get different hashes on command line with -r and '-f'.

Could someone point out why the hashes would be different using the two methods above? Is there a way to run PHP on command line where I can type the code without entering it in a file, and see output as if it were run inside a file/Apache? I use the command line for quick snippet testing when step-through code debugging is not set up.

Thanks.

PS: I am using PHP 5.2.11 with Suhosin-Patch 0.9.7 (cli) on OpenSUSE 11.1.

+8  A: 

When you run $ php -r "print sha1('$1S*90');" on your bash shell, bash is interpreting $1 as a shell variable, which is probably empty unless you have set it.

So PHP sees just this: print sha1('S*90');

The result of which is: 77cd8b48ceca53e018f80536b0a44c5b6710425f, the value you were getting first time. :)

You can escape it like this:

$ php -r "print sha1('\$1S*90');"
Ben James
Thanks, Ben. I missed that the Bash might be interpreting it. I fell in the same trap that I point my coworkers to look for :)Escaping helps when there are a few characters to escape and we know the characters that the shell may interpret. Python and Ruby can run in interpreter mode on command line like Bash does, thereby escaping shell interpretation issue. Would you happen to know if PHP can be executed that way? It could be something like Yii console tool, yiic, without Yii dependency.
SSJ
`$ php -a` gives you a (somewhat limited) interactive mode
Ben James
Yes, I have tried `$ php -a` in the past but could not figure out how to show the execution result. I did some searching after you pointed out. It seems that we need to use `<?php` before PHP code can be executed. Option `-a` is a workable solution. I can cut and paste and run multi-line PHP code with local variables instead of worrying about shell escaping and pairing quotes with `-r` option. Thanks for sharing.
SSJ
Could the person who downvoted this please let me know what the error is? Thanks.
Ben James
A: 

The $ and or * in your string will be interpreted, maybe because of the " instead of '

powtac