Page 1 of 1

Processing Tomcat Users XML with PHP

Posted: Sun Mar 02, 2008 7:27 am
by canuck
Hi. I am new to php and hope my question is not inappropriate here. I am trying to write php code to edit an xml file containing users and roles in tomcat. The code is working, but believe there must be a better way.

Code: Select all

<?php
// This is the content of the file
$xmlstr='<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="superuser"/>
  <role rolename="curator"/>
  <role rolename="supercurator"/>
  <role rolename="accountant"/>
  <role rolename="superaccountant"/>
 
  <user username="superuser" password="secret" roles="superuser"/>
  <user username="curator" password="curator" roles="curator"/>
  <user username="supercurator" password="supercurator" roles="supercurator"/>
  <user username="accountant" password="accountant" roles="accountant"/>
  <user username="superaccountant" password="superaccountant" roles="superaccountant"/>
</tomcat-users>
';
/* The string above is actually read from an xml file - I leave the code in for reference
$filename = "tomcat-users.xml";
if (!($fp = fopen($filename, "r"))) { die("cannot open ".$filename); }
 
while(!feof($fp)) { 
    $xmlstr = $xmlstr . fgets($fp, 4096); 
    } 
fclose ($fp); 
*/
 
$xml = new SimpleXMLElement($xmlstr);
 
$i = 0;
$roles = "";
foreach($xml->role as $role) {
// Do not know how many roles there are, loop through all one by one and save
    foreach ($xml->role[$i]->attributes() as $a => $b) {
        $roles = $roles . $b . " ";
        }
    $i++;
    }
 
// Now process users - do not know how many, so go through all
 
$i = 0;
 
foreach($xml->user as $user) {
// roles is an attribute of user (as well as username and password)
 
    foreach ($xml->user[$i]->attributes() as $a => $b) {
        echo $a,'="',$b,"\"\n";
        if ($a === "roles") {
            // Is the attribure roles member of allowed roles ?
            echo "Processing role $b \n";
            // Avoid confusing user and superuser 
            $needle = $b . " ";
            if (strpos($roles, $needle) !== false) {
                echo "Role $b valid\n";
                   } else {
                echo "Role $b invalid\n";
                }
            }
        }
        $i++;
    }
?> 
The major questions are:
Could I somehow check the roles validity better (directly tying user to valid roles?
Providing I input the user name, can I change the password and/or role and write the file back ?

Thanks