Search code examples
phparraysif-statementcomparisonfile-get-contents

PHP not comparing with arraypart


I am creating a simple script which searches through a textfile for the correct combination but it just doesn't work. I troubleshooted everything but all the parts just worked, but still the whole script isn't working and I don't know how to fix it.

code:

<html>

<form>
<input type="text" name="input" placeholder="hash"><button type="submit">Crack!</button>
</form>
<?php
$input = $_GET["input"]; // pulling input from url

$hashes = file_get_contents("hashes.txt"); // loading hashes

$hasharray = explode(";", $hashes); // separating hashcombos

$arraynum = count($hasharray); // counting number of hashcombos

// defining loop
$loopnum = 0;
while($loopnum < $arraynum) {
    $combo = $hasharray[$loopnum]; // selecting hashcombo
    $comboarray = explode("|", $combo); // separating hashcombo
    $text = $comboarray[0];
    $hash = $comboarray[1];

    // cecking if hash matches
    if($hash === $input) {
        echo("Hash: $hash");
        echo("<br>");
        echo("Text: $text");
    }

    $loopnum = $loopnum + 1; // updating loop

}
?>
</html>

example hashes.txt:

test|example;
example|test;

Solution

  • Your file contains newlines, that are also invisible characters. For example:

    test|example;(newline here)
    example|test;
    

    You split the lines in your file by using the ;, but that does not remove the newline characters. Considering the comments in your question, you have newlines in your results causing your comparisons to fail. That said, I suggest the following solution right after loading the hashes to remove the newline characters:

    $hashes = preg_replace("/[\r\n]/", "", $hashes);
    

    Which will result in a string like:

    test|example;example|test;
    

    The rest of your code will work as expected.