ashah142
ashah142

Reputation: 580

read file and get specific contents and echo them (php)

I have a file (passwords_admin.txt) that contains information like this:

# This file is for storing administrative
# .passwords_user in the same directory.
#
# NOTE (Important):
# format: <server type> <keyword>[,<keyword>...] <server name> <login name> <password>      
[<location> [<host> <port>] ]
# The first entry for a given server will be the default user.
# Current keywords:
# livepw - The password change script will change the sa password on this server to the 
new live password
# devpw - The password change script will change the sa password on this server to the 
new dev password
## mysql servers
##
# Do not remove the next line
# ----------- MySQL Instances start here ----------
mysql 1515,dev,devpw,online,ldap_pwd dev-exodus-01 dba_admin B66AF9 166.77.177.241 3306
mysql 1515,dev,devpw,online,ldap_pwd dev-exodus-01 dba_query 83939E 166.77.177.241 3306
mysql 1515,dev,devpw,online,ldap_pwd qa-exodus-01 dba_admin B66AF9 166.77.189.125 3306
mysql 1515,dev,devpw,online,ldap_pwd qa-exodus-01 dba_query 583939E 166.77.189.125 3306
...
...

Data is stored in this formate:format: <server type> <keyword>[,<keyword>...] <server name> <login name> <password> [<location> [<host> <port>] ]

Now, I want to copy and print hostname and keyword(devpw or livepw) of a specific instance.

For example, for instance dev-exodus-01. I want to print it's hostname which 166.77.177.241 and it's keyword devpw. Or Is there any way I can store these values in variables and I can use them later?

I tried this, but obviously it is not working.

$file = fopen("passwords_admin.txt", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof($file)) {
    $line = fgets($file, 1024);

    if (preg_match("@devpw(.*)@i", $line, $out)) {
        $title = $out[1];
        echo $title;
        echo "<br/>";
    }
}

Any suggestions ?

Upvotes: 0

Views: 153

Answers (1)

andrewsi
andrewsi

Reputation: 10732

This should point you in the right direction:

if (preg_match("@devpw(.*)@i", $line)) {
    $data = explode (" ", $line);
    $keywords = $data[1];
    $hostname = $data[5];
}

It splits the line into an array, based on your format. The $hostname is set to the sixth entry, and $keywords are in the second one.

You'll need to do something similar with $keywords to get the individual keywords, and you'll need to figure out a way of either just finding the one line from the config file you want, or of storing multiple rows of data - an array of associative arrays might work.

Upvotes: 1

Related Questions