Page 1 sur 2

Modifier fichier .Ini en php

Posté : 15 juin 2016, 15:38
par mouhssine
bonjour ,

a partir d'une page php je veux modifier des valeur dans un fichier ini à partir des valeurs saisies dans des input d'une form

le fichier ini s'appelle :exemple.ini

[SOCIETE]

BUDGET=100000008

NOM=Toto

[NIVEAU]

NIV3=Service

NIV4=Division

le code de ma fenêtre est comme suit:
<form name="form1"  id="form1" method="post"   action="" > 
 
<td style="width: 100px; font-size: 12px;" class="titre">Nom de l'entreprise</td>
<input id="Txt_Nom_Ent" type="text" maxlength="30" value="" />
 
<td  style="width: 100px; font-size: 12px;" class="titre">Mt Budget Téléphonique</td>
 
<input id="Txt_M_Budget" type="text" maxlength="30" value="" />
 
<td  style="width: 100px; font-size: 12px;" class="titre">Niveau 3</td>
<input id="Txt_Niveau3" type="text" maxlength="20" value=""/>
<td  style="width: 100px; font-size: 12px;" class="titre">Niveau 4</td>
 
<input id="Txt_Niveau4" type="text" maxlength="20" value=""/>
 
<a style="color:#000;"  type="submit" class=""  name="item">Modifier</a>
                 
 
<a style="color:#000;" class="button action3"  type="reset" id="item" >Fermer</a>
 
</form>


je veux lorsque je saisie les valeur de mes input (Nom de l'entreprise,Mt Budget Téléphonique,Niveau 3,Niveau 4 ) et j'appuie sur le bouton Modifier

les valeurs correspondantes(NOM,BUDGET,NIV3,NIV4) dans mon fichier ini changent. merci

Re: Modifier fichier .Ini en php

Posté : 15 juin 2016, 16:30
par moogli
salut,

si ton fichier n'est pas amené à évolué le plus simple est surement un template du ficher à écrire et de faire des replaces des valeurs.

Un truc dans le genre. (A tester bien sur ;) )
<?php
$iniTmpl = <<<iniTmpl
[SOCIETE]
BUDGET={budget}
NOM={nom}

[NIVEAU]
NIV3={n3}
NIV4={n4}
iniTmpl;

$tabSearch = ['{budget}','{nom}','{n3}','{n4}'];
$tabData = [$_POST['Txt_M_Budget'],$_POST['Txt_Nom_Ent'],$_POST['Txt_Niveau3'],$_POST['Txt_Niveau4']];
$fileContent = str_ireplace($tabSearch,$tabData,$iniTmpl);
file_put_contents('exemple.ini',$fileContent);
Sinon après faut te faire toi même l'objet ou le fonction qui va alimenter le fichier.
Dans la doc de la par_ini_file y a des exemples
http://php.net/manual/fr/function.parse ... .php#78221
http://php.net/manual/fr/function.parse ... .php#94414

@+

Re: Modifier fichier .Ini en php

Posté : 15 juin 2016, 16:51
par mouhssine
je vais essayer ton code ,merci

Re: Modifier fichier .Ini en php

Posté : 15 juin 2016, 17:13
par @rthur
Bonjour,

PHP a une fonction native pour lire les fichiers ini et retourner les informations sous la forme d'un tableau facilement exploitable en PHP :
https://secure.php.net/manual/fr/functi ... i-file.php

Un contributeur a réalisé la fonction inverse, pour enregistrer un tableau sous la forme de fichier ini:
https://secure.php.net/manual/fr/functi ... php#111459

Donc tu pourrais charger ton fichier ini avec parse_ini(), modifier les valeurs que tu veux, puis avec put_ini_file() le réenregistrer dans le fichier.

Re: Modifier fichier .Ini en php

Posté : 15 juin 2016, 18:02
par mouhssine
je vais voir tes liens et essayer merci

Re: Modifier fichier .Ini en php

Posté : 15 juin 2016, 18:10
par Naroth
Bonjour,

Merci @rthur ,
je cherchais une méthode similaire pour aller lire un fichier de propriétés, sans parcourir tout le fichier, ni utiliser de shell_exec.
Et ça marche bien.

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 12:09
par mouhssine
j 'ai eu des messages d'erreurs avec les 2 lignes suivantes
$tabSearch = ['{budget}','{nom}','{n3}','{n4}'];
$tabData = [$_POST['Txt_M_Budget'],$_POST['Txt_Nom_Ent'],$_POST['Txt_Niveau3'],$_POST['Txt_Niveau4']];

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 12:16
par @rthur
Quels messages ?

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 12:33
par moogli
a vu de nez je dirais :
soit un problème de syntaxe a cause d'une version de php trop vieille :)
soit index inexistant dans le tableau POST lors de l'affichage du formulaire la première fois ? (ou alors le copier collé du formulaire en haut a merdé ;) ).

si c'est sur les deux lignes je penche pour le 1er cas (sinon la syntaxe est correcte).

@+

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 12:42
par mouhssine
oui moogli ,cé problème de synthaxe

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 12:57
par moogli
peux tu indiquer les messages d'erreurs ?
c'est pas simple de deviner !

a priori tu as une version de php inférieure à 5.4 (c'est vieux et plus maintenu depuis plus de deux ans ça ;) http://php.net/supported-versions.php ).
si oui remplace l'utilisation de [] par array().

La syntaxe tableau en php http://php.net/manual/fr/language.types.array.php

@+

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 13:17
par mouhssine
j’utilise la version php-5.2.6-Win32

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 13:51
par @rthur
j’utilise la version php-5.2.6-Win32
Ohhhh une version de 2008 !
Va peut être falloir envisager une mise à jour, non ? :D

Re: Modifier fichier .Ini en php

Posté : 16 juin 2016, 14:47
par mouhssine
mon fichier exemple.ini ne contient pas seulement les valeurs que j'ai mentionné au début , j'ai écris seulement les valeurs que je veux changer , est ce que la solution de moogli est la bonne.
j'ai vu un exemple de modification de fichier ini dans un forum ,que je l'ai adapté à mon cas , les valeurs sont modifiées mais mon nouveau fichier contient seulement les valeurs modifiées les autres sont supprimées . est ce que je peux envoyer ce programme pour m'aider à corriger l'erreur.

Re: Modifier fichier .Ini en php

Posté : 17 juin 2016, 18:00
par mouhssine
je pose mon code , qui change les valeurs voulues , mais le problème il vide le fichier et laisse seulement les valeurs modifiées

mon fichier ini :

[GENERAL]
CODE_NATIONAL=N
CODE_REGION_INSTALLATION=011
CODE_ZONE_INSTALLATION=011
CODE_PAYS_INSTALLATION=137
CODE_GSM=200
PQMC_INSTALLATION=02
MT_IMPULSION=0.8
DUREE_MIN=1
DUREE_MAX=9999
DUREE_SONNERIE=0
COUT_UTILISE=0
NBRE_ESSAI_LOGIN=3
COEF_FACT=1
CUMUL=1
MONNAIE=DH
SOCIETE=Telepac Technology
POSTE_DEPLACE=0
IMPULTION=1
BPwd=OUI
NB_CARAC_CRYPTE=0
TYPE_APPLICATION=2

[NIVEAU]
NIV3=Service
NIV4=Devision
NIV1=Direction
NIV2=Département
NIV5=Cellule

[FONCTIONS]
FONCTION0=Directeur
FONCTION1=Directeur Adjoint
FONCTION2=Responsable
FONCTION3=Ingenieur
FONCTION4=Salarié

[SOCIETE]
BUDGET=100000008
NOM=ATLANTA

le code de la cla classe :
<?php

class ini
{
  var $fichier="exemple.ini";
  var $groupe="";
  var $item="";
  var $valeur="";
  var $fichier_ini=array();
  function m_fichier($arg)
  {
     $this->fichier=$arg;
     $this->fichier_ini=null;
     $this->fichier_ini=array();
     // Pour utiliser parse_ini_file() par défaut, enlevez /* et */, sinon supprimez ce commentaire (conseillé)
     /*if(false!==($array=@parse_ini_file($arg, TRUE)))
     {
        $this->fichier_ini=$array;
     }
     else*/if(file_exists($arg) && $fichier_lecture=file($arg))
     {
       foreach($fichier_lecture as $ligne)
       {
         $ligne_propre=trim($ligne);
         if(preg_match("#^\[(.+)\]$#",$ligne_propre,$matches))
         {
           $groupe_curseur=$matches[1];
         }
         else
         {
           if($ligne_propre[0]!=';' && $tableau=explode("=",$ligne,2))
           {
             $this->fichier_ini[$groupe_curseur][$tableau[0]]=rtrim($tableau[1],"\n\r");
           }
         }
       }
     }
     $this->valeur=$this->fichier_ini[$this->groupe][$this->item];
  }
  function m_groupe($arg)
  {
     $this->groupe=$arg;
     $this->valeur=$this->fichier_ini[$this->groupe][$this->item];
     return true;
  }
  function m_item($arg)
  {
     $this->item=$arg;
     $this->valeur=$this->fichier_ini[$this->groupe][$this->item];
     return true;
  }
  function m_put($arg, $arg_i=false, $arg_g=false, $arg_f=false)
  {
     if($arg_f!==false) $this->m_fichier($arg_f);
     if($arg_g!==false) $this->m_groupe($arg_g);
     if($arg_i!==false) $this->m_item($arg_i);
     $this->fichier_ini[$this->groupe][$this->item]=$arg;
     $this->valeur=$arg;
     return $this->fichier." ==> [".$this->groupe."] ".$this->item."=".$this->valeur;
  }
  function m_count($arg_gr=false)
  {
     if($arg_gr===false)
     return array(1=>$gr_cou=count($this->fichier_ini), 0=>$itgr_cou=count($this->fichier_ini, COUNT_RECURSIVE), 2=>$itgr_cou-$gr_cou);
     else
     return count($this->fichier_ini[$arg_gr]);
  }
  function array_groupe($arg_gr=false)
  {
     if($arg_gr===false)
     $arg_gr=$this->groupe;
     return $this->fichier_ini[$arg_gr];
  }
  function save()
  {
     $fichier_save="";
     foreach($this->fichier_ini as $key => $groupe_n)
     {
         $fichier_save.="
[".$key."]";
         foreach($groupe_n as $key => $item_n)
         {
             $fichier_save.="
".$key."=".$item_n;
         }
     }
     $fichier_save=substr($fichier_save, 1);
     if(file_exists($this->fichier) && reset(explode('.',phpversion()))>=5)
     {
             if(false===file_put_contents($this->fichier, $fichier_save))
             {
                die("Impossible d'&eacute;crire dans ce fichier (mais le fichier existe).");
             }
     }
     else
     {
             $fichier_ouv=fopen($this->fichier,"w+");
             if(false===fwrite($fichier_ouv, $fichier_save))
             {
                die("Impossible d'&eacute;crire dans ce fichier (Le fichier n'existe pas).");
             }
             fclose($fichier_ouv);
     }
     return true;
  }
  function clear()
  {
      $this->fichier="";
      $this->groupe="";
      $this->item="";
      $this->valeur="";
      $this->fichier_ini=null;
      $this->fichier_ini=array();
  }
  function s_fichier()
  {
     $return=$this->fichier;
     if(file_exists($this->fichier)) unlink($this->fichier);
     $this->fichier="";
     $this->valeur="";
     return "fichier(".$return.") supprim&eacute;.";
  }
  function s_groupe()
  {
     $return=$this->groupe;
     if(isset($this->fichier_ini[$this->groupe])) unset($this->fichier_ini[$this->groupe]);
     $this->groupe="";
     $this->valeur="";
     return "groupe(".$return.") supprim&eacute;.";
  }
  function s_item()
  {
     $return=$this->item;
     if(isset($this->fichier_ini[$this->groupe][$this->item])) unset($this->fichier_ini[$this->groupe][$this->item]);
     $this->item="";
     $this->valeur="";
     return "item(".$return.") supprim&eacute;.";
  }

  function print_curseur()
  {
     echo "Fichier : <b>".$this->fichier."</b><br />";
     echo "Groupe : <b>".$this->groupe."</b><br />";
     echo "Item : <b>".$this->item."</b><br />";
     echo "Valeur : <b>".$this->valeur."</b><br />";
     return true;
  }
  function print_dossier()
  {
     if(is_dir($this->fichier)) {
     echo "<img src='dir.png' alt='Dossier' /><span style='position:relative; top:-10px;font-size:20px; font-weight:bold;'>".$this->fichier."</span><br />";
     if($handle=opendir($this->fichier))
     {
        while(false!==($file=readdir($handle)))
        {
            if(substr($file, -4, 4)==".ini")
            {
               echo "&nbsp;&nbsp;<a href='?fichier=".$file."'><img src='iniicone.png' alt='Ini' style='border:none;' /></a>&nbsp;".$file."<br />";
            }
        }
        closedir($handle);
     }
     return true; }
     else { echo "L'élément sélectionné n'est pas un dossier"; return false; }
  }
  function print_fichier()
  {
     if(file_exists($this->fichier) && is_file($this->fichier) && $fichier_lecture=file($this->fichier))
     {
       foreach($fichier_lecture as $ligne)
       {
         $ligne=preg_replace("#\s$#","",$ligne);
         if(preg_match("#^\[.+\]\s?$#",$ligne))
         $groupe=false;
         if(preg_match("#^\[".preg_quote($this->groupe, "#")."\]$#",$ligne))
         {
           $echo.= "<span style='background-color:aqua;'>".htmlspecialchars($ligne)."</span><br />";
           $groupe=true;
         }
         elseif($groupe==true && $this->item==reset(explode("=",$ligne)))
           $echo.= "<span style='background-color:yellow;'>".htmlspecialchars($ligne)."</span><br />";
         else
           $echo.= htmlspecialchars($ligne)."<br />";
       }
           echo $echo;
     }
     else
     {
       echo "Le fichier n'existe pas ou est incompatible";
     }
     $this->valeur=$this->fichier_ini[$this->groupe][$this->item];
     return true;
  }
  function m_valeur($arg_item, $arg_groupe)
  {
     return $this->fichier_ini[$arg_groupe][$arg_item];
  }
}

?>



mon code php suivi du html
<?php

include('C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\EagleWeb\class.php');
 
session_start();
if(isset($_SESSION['ini']))
$ini_objet=unserialize($_SESSION['ini']);
else
$ini_objet=new ini();
 
if(isset($_GET['fichier']))
{
    $dossier=$ini_objet->fichier;
    $dossier=preg_replace('#/$#','',$dossier).'/';
    $ini_objet->m_fichier($dossier.$_GET['fichier']);
    header('Location:./ini.php5');
}
if(isset($_POST['clear']))
{
    $ini_objet->clear();
}

$groupe1='SOCIETE';
$groupe2='NIVEAU';
$item1='NIV1';
$item2='NOM';
$item3='BUDGET';

if(isset($_POST['valeur']))
{
    if($_POST['valeur']=='Modifier')
    {
		
        $ini_objet->m_put(stripslashes($_POST['Txt_Name']),$item2,$groupe1);
		$ini_objet->m_put(stripslashes($_POST['Txt_Budget']),$item3,$groupe1);
		$ini_objet->m_put(stripslashes($_POST['Txt_Niveau']),$item1,$groupe2);
        $ini_objet->save();
    }
    
}

 
$_SESSION['ini']=serialize($ini_objet);

 
?>
<html>
<head>
<title>Traitement INI</title>
<style>
form
{
    margin:0px;
    padding:0px;
}
fieldset
{
    margin-right:10px;
    margin-bottom:8px;
    border:1px black solid;
}
legend
{
    color:#333333;
    font-style:italic;
    font-weight:bolder;
    font-size:18px;
}
</style>
</head>
<body>
<div style="float:right;">
  <div style="width:400px; padding:6px; margin-right:12px; border:1px solid black;">
    <div style="float:right; text-align:right;">
      <?php
      $stat=$ini_objet->m_count();
      echo '<strong>'.$stat[1].'&eacute;l&eacute;ments</strong> dans ce fichier<br />
      dont <strong>'.$stat[0].'groupes</strong> et <strong>'.$stat[2].' items</strong>.<br />
      <strong>'.$ini_objet->m_count($ini_objet->groupe).' items</strong> dans ce groupe.';
      ?>
    </div>
    <u><i><b>Information sur le curseur</b></i></u><br />
    <?php $ini_objet->print_curseur(); ?>
  </div>
  <div style="width:400px; height:400px; overflow:auto; padding:6px; margin-top:12px; margin-right:12px; border:1px solid black;">
    <u><i><b>Aper&ccedil;u du <?php if(is_dir($ini_objet->fichier)) echo 'dossier'; else echo 'fichier'; ?></b></i></u><br /><br />
    <span style="font-family:courier; white-space:nowrap;"><?php if(is_dir($ini_objet->fichier)) $ini_objet->print_dossier(); else $ini_objet->print_fichier(); ?></span>
  </div>
</div>



<fieldset><legend>Valeur</legend>
  <form method="post" action="">
    <label>Nom : <input type="text" name="Txt_Name" /></label><br />
    <label>Budget : <input type="text" name="Txt_Budget" /></label><br />
    <label>Niveau : <input type="text" name="Txt_Niveau" /></label><br />
    <input type="submit" name="valeur" value="Modifier" />
  </form>
  
</fieldset>
<br />

</body>
</html>
j'attend votre aide merci