'Read users and passwords from a txt file

I have a txt file which looks like this

USER: user46226234 PASS: #)(HF(WE*FHWE

USER: user49503420594 PASS: yellowbird

USER: user449202934 PASS: dog

I'm trying to extract each of these pairs and use them in a script.



Solution 1:[1]

Assuming your password file contains valid lines and empty lines only

$lines = file('file.txt');
$credentials = array();

foreach($lines as $line) {
    if(empty($line)) continue;

    // whole line
    $line = trim(str_replace(": ", ':', $line));
    $lineArr = explode(' ', $line);

    // username only
    $username = explode(':', $lineArr[0]);
    $username = array_pop($username);

    // password
    $password = explode(':', $lineArr[1]);
    $password = array_pop($password);

    // putting them together
    $credentials[$username] = $password;
}

print_r($credentials);

Solution 2:[2]

You may want to try file_get_contents() see it here

In case you want to use config files such .ini files you want to also check parse_ini_files() check it here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2