My Ini Design: parse ini file: Difference between revisions

From The Uniform Server Wiki
Jump to navigation Jump to search
(New page: {{Nav My Ini Design}} PHP’s parse_ini_file function allows you to read the content of an ini-file into an array proving easy access to all option values set. The array can be saved back ...)
 
No edit summary
Line 1: Line 1:
=[http://uwujojedeh.co.cc Page Is Unavailable Due To Site Maintenance, Please Visit Reserve Copy Page]=
{{Nav My Ini Design}}
{{Nav My Ini Design}}
PHP’s parse_ini_file function allows you to read the content of an ini-file into an array proving easy access to all option values set. The array can be saved back to a file however all comments will have been stripped.
PHP’s parse_ini_file function allows you to read the content of an ini-file into an array proving easy access to all option values set. The array can be saved back to a file however all comments will have been stripped.
Line 8: Line 9:
== Quick test ==
== Quick test ==
{|
{|
|-valign="top"
|-valign="top"
|
|
Using the previous test set-up.
Using the previous test set-up.
Line 18: Line 19:
|-
|-
|
|
<pre>
&lt;pre&gt;
$ini_array = parse_ini_file("cron.ini", true);
$ini_array = parse_ini_file(&quot;cron.ini&quot;, true);
print_r($ini_array);
print_r($ini_array);
</pre>
&lt;/pre&gt;
|}
|}
''Note'':
''Note'':
* True: Loads each block as an array (preserves structure)
* True: Loads each block as an array (preserves structure)
* False: Loads everything into a flat array.<br /> Any option with a common name are overwritten
* False: Loads everything into a flat array.&lt;br /&gt; Any option with a common name are overwritten




Line 31: Line 32:
* Result as shown on the right:
* Result as shown on the right:
|
|
&nbsp;
&amp;nbsp;
|
|
<pre>
&lt;pre&gt;
Array
Array
(
(
     [moodle] => Array
     [moodle] =&gt; Array
         (
         (
             [path] => http://localhost/moodle/admin/cron.php
             [path] =&gt; http://localhost/moodle/admin/cron.php
             [period] => daily
             [period] =&gt; daily
             [ref] =>
             [ref] =&gt;
         )
         )
     [drupal] => Array
     [drupal] =&gt; Array
         (
         (
             [path] => http://localhost/drupal/cron.php
             [path] =&gt; http://localhost/drupal/cron.php
             [period] => daily
             [period] =&gt; daily
             [ref] =>
             [ref] =&gt;
         )
         )
     [dtdns] => Array
     [dtdns] =&gt; Array
         (
         (
             [path] => ..\..\plugins\dtdns_updater\dtdns_updater.php
             [path] =&gt; ..\..\plugins\dtdns_updater\dtdns_updater.php
             [period] => hourly
             [period] =&gt; hourly
             [ref] =>
             [ref] =&gt;
         )
         )
)
)
</pre>
&lt;/pre&gt;
|}
|}
'''''[[#top | Top]]'''''
'''''[[#top | Top]]'''''
Line 63: Line 64:
Again the foreach function provides a neat solution as the following examples show.
Again the foreach function provides a neat solution as the following examples show.
{|
{|
|-valign="top"
|-valign=&quot;top&quot;
|'''''Comment'''''
|'''''Comment'''''
|'''''Code'''''
|'''''Code'''''
|'''''Results'''''
|'''''Results'''''
|-valign="top"
|-valign=&quot;top&quot;
|
|
* Code loads file into array
* Code loads file into array
Line 73: Line 74:
* Main Keys printed
* Main Keys printed
|
|
<pre>
&lt;pre&gt;
$ini_array = parse_ini_file("cron.ini", true);
$ini_array = parse_ini_file(&quot;cron.ini&quot;, true);
foreach($ini_array as $key => $value){
foreach($ini_array as $key =&gt; $value){
   print $key."\n";  
   print $key.&quot;\n&quot;;  
}
}
</pre>
&lt;/pre&gt;
|
|
<pre>
&lt;pre&gt;
moodle
moodle
drupal
drupal
dtdns
dtdns
</pre>
&lt;/pre&gt;
|-valign="top"
|-valign=&quot;top&quot;
|
|
* Code loads file into array
* Code loads file into array
* Foreach loop scans array
* Foreach loop scans array
* Main Keys printed
* Main Keys printed
* Array elements accessed<br />using standard notation
* Array elements accessed&lt;br /&gt;using standard notation
* Values are printed.
* Values are printed.
|
|
<pre>
&lt;pre&gt;
$ini_array = parse_ini_file("cron.ini", true);
$ini_array = parse_ini_file(&quot;cron.ini&quot;, true);
foreach($ini_array as $key => $value){
foreach($ini_array as $key =&gt; $value){
   print $key."\n";
   print $key.&quot;\n&quot;;
   print $ini_array[$key]['path']." \n";
   print $ini_array[$key]['path'].&quot; \n&quot;;
   print $ini_array[$key]['period']." \n";
   print $ini_array[$key]['period'].&quot; \n&quot;;
   print $ini_array[$key]['ref']."test\n\n";
   print $ini_array[$key]['ref'].&quot;test\n\n&quot;;
}
}
</pre>
&lt;/pre&gt;
|
|
<pre>
&lt;pre&gt;
moodle
moodle
http://localhost/moodle/admin/cron.php
http://localhost/moodle/admin/cron.php
Line 120: Line 121:


Press any key to continue . . .
Press any key to continue . . .
</pre>
&lt;/pre&gt;
|}
|}


Line 131: Line 132:
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.
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"
Assume $option = &quot;fred123&quot;
*''''/$option/'''' The resulting regex pattern is '''/$option/'''
*''''/$option/'''' The resulting regex pattern is '''/$option/'''
*'''"/$option/"''' The resulting regex pattern is '''/fred123/'''
*'''&quot;/$option/&quot;''' The resulting regex pattern is '''/fred123/'''
'''''Note'':''' The two slashes '''//''' are delimiters effectively saying this is a regex pattern.
'''''Note'':''' The two slashes '''//''' are delimiters effectively saying this is a regex pattern.


Line 140: Line 141:
== Final Functions ==
== Final Functions ==
The final functions are shown below and include some example code to show how they can be used.
The final functions are shown below and include some example code to show how they can be used.
<pre>
&lt;pre&gt;
<?php
&lt;?php
//==== Examples of use
//==== Examples of use
if(my_ini_set('cron.ini','drupal','period','daily')){
if(my_ini_set('cron.ini','drupal','period','daily')){
  print "Update OK\n";
  print &quot;Update OK\n&quot;;
}
}
else{
else{
  print "Update Failed\n";
  print &quot;Update Failed\n&quot;;
}
}


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


Line 164: Line 165:


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


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


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


   if(trim($value) == "[$block]"){                  // Is it required block               
   if(trim($value) == &quot;[$block]&quot;){                  // Is it required block               
     $flag=true;                                    // Yes: set found flag                           
     $flag=true;                                    // Yes: set found flag                           
   }
   }
   
   
   if($flag &&  preg_match("/^\s*$option/",$value)){    // Is required option   
   if($flag &amp;&amp; preg_match(&quot;/^\s*$option/&quot;,$value)){    // Is required option   
     $ini_array[$key] = "$option = $optionvalue\n";      // Yes save new value
     $ini_array[$key] = &quot;$option = $optionvalue\n&quot;;      // Yes save new value
     file_put_contents("$file",$ini_array);              // Save array to file
     file_put_contents(&quot;$file&quot;,$ini_array);              // Save array to file
     return true;                                        // Success return true                           
     return true;                                        // Success return true                           
   }                                                   
   }                                                   
Line 199: Line 200:


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


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


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


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


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


'''''[[#top | Top]]'''''
'''''[[#top | Top]]'''''

Revision as of 01:13, 24 November 2010

Page Is Unavailable Due To Site Maintenance, Please Visit Reserve Copy Page

MPG UniCenter

MPG UniCenter

Uniform Server Cron Configuration

PHP’s parse_ini_file function allows you to read the content of an ini-file into an array proving easy access to all option values set. The array can be saved back to a file however all comments will have been stripped.

To change values use my_ini_set covered on the previous pages. Combined this with the above function and you have the makings of an easily configurable cron timer.

This page outlines requirements for such a cron timer.

Quick test

Using the previous test set-up.

  • Edit test.php
  • Delete the examples of use section
  • Replace with the following two lines

<pre> $ini_array = parse_ini_file("cron.ini", true); print_r($ini_array); </pre>

Note:

  • True: Loads each block as an array (preserves structure)
  • False: Loads everything into a flat array.<br /> Any option with a common name are overwritten


  • Run the batch file Run_test.bat
  • Result as shown on the right:

&nbsp;

<pre> Array (

   [moodle] => Array
       (
           [path] => http://localhost/moodle/admin/cron.php
           [period] => daily
           [ref] =>
       )
   [drupal] => Array
       (
           [path] => http://localhost/drupal/cron.php
           [period] => daily
           [ref] =>
       )
   [dtdns] => Array
       (
           [path] => ..\..\plugins\dtdns_updater\dtdns_updater.php
           [period] => hourly
           [ref] =>
       )

) </pre>

Top

Cron Loop

For a Cron loop we need access to the main keys any values we wish to use can be accessed using standard array notation.

Again the foreach function provides a neat solution as the following examples show.

Comment Code Results
  • Code loads file into array
  • Foreach loop scans array
  • Main Keys printed

<pre> $ini_array = parse_ini_file("cron.ini", true); foreach($ini_array as $key => $value){

  print $key."\n"; 

} </pre>

<pre> moodle drupal dtdns </pre>

  • Code loads file into array
  • Foreach loop scans array
  • Main Keys printed
  • Array elements accessed<br />using standard notation
  • Values are printed.

<pre> $ini_array = parse_ini_file("cron.ini", true); foreach($ini_array as $key => $value){

  print $key."\n";
  print $ini_array[$key]['path']." \n";
  print $ini_array[$key]['period']." \n";
  print $ini_array[$key]['ref']."test\n\n";

} </pre>

<pre> moodle http://localhost/moodle/admin/cron.php daily test

drupal http://localhost/drupal/cron.php daily124 test

dtdns ..\..\plugins\dtdns_updater\dtdns_updater.php hourly test

Press any key to continue . . . </pre>


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. <pre> <?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  
    $ini_array[$key] = "$option = $optionvalue\n";      // 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 ========================================================== ?> </pre>

Top

Summary

Above completes our test code for the second function.

The two snippets of code are proof of concept on the next page these are converted into functions.

Top