My Ini Design: Final Functions

From The Uniform Server Wiki
Jump to navigation Jump to search

MPG UniCenter

MPG UniCenter

Uniform Server Cron Configuration

Previous two pages covered code snippets for two functions my_ini_set and my_ini_get.

This page shows that code converted into practical functions.

Code differences

Main difference between code snippets and final functions is the removal of test code.

  • There are no longer two separate files, input and output files now use the same file. If you recall the output file was required for testing.
  • Static values have been replaced with variables.
  • Print statements used for testing have been removed.
  • Add code to my_ini_set now preservers comments

Top

Issues

When converting static regex patterns to use variables it looks tricky.

In reality its quite simple anything enclosed in single quotes is treated by PHP as being literal (use as seen). If enclosed in double quotes PHP replaces all variables with their current value.

Assume $option = "fred123"

  • '/$option/' The resulting regex pattern is /$option/
  • "/$option/" The resulting regex pattern is /fred123/

Note: The two slashes // are delimiters effectively saying this is a regex pattern.

Top

Final Functions

The final functions are shown below and include some example code to show how they can be used.

<?php
//==== Examples of use
if(my_ini_set('cron.ini','drupal','period','daily')){
 print "Update OK\n";
}
else{
 print "Update Failed\n";
}

print my_ini_get('cron.ini','moodle','path')."\n";
//==== End Examples of use

//=== my_ini_set ==============================================================
// Sets an option value in a configuration file
// Inputs:
// $file        Path to file including file name
// $block       Name of block excluding []
// $option      Name of option
// $optionvalue New value of option
// Outputs:
// Returns true on success or false on failure 

function my_ini_set($file,$block,$option,$optionvalue){
 $ini_array = file("$file");                         // Read file into array

 $flag=false;                                        // Set found flag
 foreach($ini_array as $key => $value){              // Scan array line by line

   if($flag &&  preg_match('/^\s*\[/',$value)){      // Is it a new block 
     $flag=false;                                    // Yes: Rest flag
   }

   if(trim($value) == "[$block]"){                   // Is it required block              
     $flag=true;                                     // Yes: set found flag                           
   }
 
   if($flag &&  preg_match("/^\s*$option/",$value)){ // Is required option 
    if(preg_match("/(\s*;.*)$/",$value,$matches)){   // Includes comment
      $comment = rtrim($matches[0]);                 // Yes: clean and save
    }
    else{                                            // No: Reset
     $comment ="";
    }
    $str= "$option = $optionvalue$comment\n";        // Build new string
    $ini_array[$key] = $str;                         // Yes save new value
    file_put_contents("$file",$ini_array);           // Save array to file
    return true;                                     // Success return true                           
   }                                                   
 }
 return false;                                       // Option not found
}//end
//=== END my_ini_set ==========================================================


//=== my_ini_get ==============================================================
// Obtains an option value from a configuration file
// Inputs:
// $file        Path to file including file name
// $block       Name of block excluding []
// $option      Name of option
// Outputs:
// Returns  Value on success
// Returns  Blank on failure 

function my_ini_get($file,$block,$option){
 $ini_array = file("$file");                         // Read file into array

 $flag=false;                                        // Set found flag
 foreach($ini_array as $key => $value){              // Scan array line by line

   if($flag &&  preg_match('/^\s*\[/',$value)){      // Is it a new block 
     $flag=false;                                    // Yes: Rest flag                                   
   }

   if(trim($value) == "[$block]"){                   // Is it required block              
     $flag=true;                                     // Yes: set found flag        
   }

   if($flag &&  preg_match("/^\s*$option/",$value)){     // Is required option  
     $str  =  trim($ini_array[$key]);                    // Yes read and clean 
     $str1 =  preg_replace("/^$option\s*=\s*/", "", $str); // Cean 
     return $str1;                                       // Retun option value 
   }                                                   
 }
 return "";                                              // Option not found 
}
//=== END my_ini_get ==========================================================
?>

Top

Summary

That completes the two functions, essentially they complement PHP’s parse_ini_file function.

To a certain extent function my_ini_get is less useful you can use parse_ini_file instead.

However my_ini_set is very useful especially if you want to use the ini-file as a form of temporary storage. Combined with parse_ini_file makes cron easily configurable as outlined on the next page.

Top