Ryan Thames
Ryan Thames

Reputation: 45

PHP Script to MD5 Hash Each Line Separately

I'm trying to create a script that can MD5 hash many lines (50,000+) quickly. I have a script I've been trying to make work, but it gives me different outputs sometimes and I can't figure out why. Any ideas?

  <?php  
     if(isset($_POST['btn'])){
            $value=$_POST['text'];
            $ids = explode(PHP_EOL, $value);
            $content = '';
            for ($i=0;$i<count($ids);$i++){
                $content .= md5($ids[$i]).'<br>';
            }

            echo nl2br($content);
     }
     ?>

When I try to hash:

apples  
bananas  
oranges  
pineapples

It results in:

265f78fc274d8428fd63dabc24400cb4  
63a63ddf49984e0f1cef336aeb6ca39c  
229b1cc78a248c6cea47fa95565dc9ca  
019b111ec0c13ed923922715bfb1670a  

But I should be getting:

daeccf0ad3c1fc8c8015205c332f5b42  
ec121ff80513ae58ed478d5c5787075b  
91b07b3169d8a7cb6de940142187c8df  
019b111ec0c13ed923922715bfb1670a  

Upvotes: 0

Views: 153

Answers (2)

ksiger
ksiger

Reputation: 323

You have whitespaces in your input data. And don't collect all 50k+ hashes in memory.
Try this

<?php  
if(isset($_POST['btn'])){
    $value=$_POST['text'];
    $ids = explode(PHP_EOL, $value);
    for ($i=0;$i<count($ids);$i++){
        echo nl2br(md5(trim($ids[$i])));
    }
}
?>

Upvotes: 0

Barmar
Barmar

Reputation: 782693

The lines in your input string are separated by \r\n, but on your server PHP_EOL is set to \n. So when you split the input into lines, there's a \r at the end of each line except the last. echo md5("apples\r"); produces 265f78fc274d8428fd63dabc24400cb4.

Use trim() to remove extra whitespace.

$content .= md5(trim($ids[$i])).'<br>';

Upvotes: 2

Related Questions