Don't like ads? PRO users don't see any ads ;-)
Guest

XMLFUN

By: a guest on May 2nd, 2012  |  syntax: PHP  |  size: 1.96 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2.  
  3.     /* Write php protected XML config file to store database credentials */
  4.     function write_db_config($string, $user = "", $pass = "", $updir = false) {
  5.  
  6.         /* Determine filename to be used */
  7.         $filename = 'db_config.xml.php';
  8.         if($updir)
  9.             $filename = "./../$filename";
  10.         else
  11.             $filename = "./$filename";
  12.  
  13.         /* Create DOM object for config XML */
  14.         $dom = new DomDocument('1.0');
  15.  
  16.         /* Add meta-root (Needed for php protection of XML files) */
  17.         $root = $dom->appendChild($dom->CreateElement('root'));
  18.  
  19.         /* Add comment to prevent browsers reading XML */
  20.         $comment = $dom->createComment("<?php die('-->Permission denied.'); ?>");
  21.         $dom->appendChild($comment);
  22.  
  23.         /* Add config root */
  24.         $dbconfig = $root->appendChild($dom->CreateElement('dbconfig'));
  25.  
  26.         /* Add elements */
  27.         $connect_string = $dbconfig->appendChild($dom->createElement('connect_string'));
  28.         $username       = $dbconfig->appendChild($dom->createElement('username'));
  29.         $password       = $dbconfig->appendChild($dom->createElement('password'));
  30.  
  31.         /* Add text to nodes */
  32.         $connect_string->appendChild($dom->createTextNode($string));
  33.  
  34.         if($user != "" )
  35.             $username->appendChild($dom->createTextNode($user));
  36.  
  37.         if($pass != "" )
  38.             $password->appendChild($dom->createTextNode($pass));
  39.  
  40.         /* Generate XML */
  41.         $dom->formatOutput = true;
  42.         $output = $dom->saveXML($comment) . "\n" . $dom->saveXML($dbconfig);
  43.  
  44.         /* Write out XML file */
  45.         $filehandle = fopen($filename, 'w');
  46.         $result = fwrite($filehandle, $output);
  47.         fclose($filehandle);
  48.  
  49.         /* Final check to see if the file was written */
  50.         if($result) {
  51.             return true;
  52.         } else {
  53.             echo("Could not write config file!");
  54.             return false;
  55.         }
  56.     }
  57.  
  58.  
  59. ?>