Reading INI files with PHP


Another easy tutorial, but it can be useful to store information outside of a MySQL database!

First up, let's make the ini file:

INI Config
  1. [SOMETHINGHERE]
  2. makesure=1
  3. youinclude=23
  4. thebrakets=345
  5. [SOMETHINGELSE]
  6. YES=12


Alright, you MUST save that as a .ini file. Now for the PHP.

PHP Code
  1. <?php
  2. $arr=parse_ini_file("Yourfile.INI",true);
  3. echo $arr['SOMETHINGHERE']['youinclude']; // echos 23
  4. echo $arr['SOMETHINGELSE']['YES']; // echos 12
  5. ?>


Just edit your .ini file as well as your .php file. Here is a full example:

Mystats.ini:

INI Config
  1. [HP]
  2. AddPerLevel=140
  3. AddPerStr=10
  4. AddPerDef=0
  5. AddPerMagi=0
  6. AddPerSpeed=0
  7. [MP]
  8. AddPerLevel=220
  9. AddPerStr=0
  10. AddPerDef=0
  11. AddPerMagi=10
  12. AddPerSpeed=0
  13. [SP]
  14. AddPerLevel=330
  15. AddPerStr=0
  16. AddPerDef=0
  17. AddPerMagi=0
  18. AddPerSpeed=20


Now, I want to get AddPerLevel under MP.

PHP Code
  1. <?php
  2. $arr=parse_ini_file("mystats.INI",true);
  3. echo $arr['MP']['AddPerLevel']; // echos 220
  4. ?>


It's a pretty simple tutorial, enjoy!
Diablosblizz's Avatar
Views:
7,977
Rating:
Posted on Wednesday 5th March 2008 at 03:41 AM
ShadowMage
ShadowMage's Avatar
Also, my random outcome i got bored with

https://hrwp.zapto.org:6020/demo/index.php
Posted on Tuesday 1st January 2008 at 02:53 AM
Diablosblizz
Diablosblizz's Avatar
That's true as well.
Posted on Monday 31st December 2007 at 06:44 PM
ShadowMage
ShadowMage's Avatar
if you use fopen it'll open the whole file, though you could most likely use file(); then check which line contains the content you want to edit.
Posted on Monday 31st December 2007 at 04:37 PM
Diablosblizz
Diablosblizz's Avatar
Zerocool, you could use the fopen function.
Posted on Monday 31st December 2007 at 02:07 PM
Dean
Dean's Avatar
good tutorial.
Posted on Sunday 30th December 2007 at 10:00 PM
ShadowMage
ShadowMage's Avatar
try looking here :) i think i saw a function/class that has a write function.

https://us2.php.net/parse_ini_file
Posted on Sunday 30th December 2007 at 09:00 PM
zerocool
zerocool's Avatar
nice tut, but i have a little question.

In PHP i can insert values on this ini files?