ho modificato il codice precedente in una classe , magari può interessare a qualcuno (con le dovute modifiche)
codice:
class dbFile {
protected $path;
protected $valori = '';
public function __construct($path = null){
if( !is_string($path) ) throw new Exception('il costruttore richiede una stringa');
if( !file_exists($path) ) throw new Exception('il file che hai specificato non esiste');
if( !is_writeable($path) ) throw new Exception('il file che hai specificato non è scrivibile');
$this->path = $path;
}
public function modifica(){
$file = file($this->path);
foreach($file as $key => $val):
$this->valori .= $val ;
endforeach;
return $this->getForm( count($file) , '20' , $this->valori ) ;
}
public function salva(){
if( !isSet($_REQUEST['dbFile']) ) throw new Exception('non hai inviato valori da salvare nel file');
if( fwrite( fopen($this->path,'w') , trim($_REQUEST['dbFile']) ) ) echo 'modifica eseguita correttamente' ;
}
private function getForm($righe , $col , $valori){
return '<form method="post" action="">' . "\n" .
"<textarea name=\"dbFile\" rows=\"{$righe}\" cols=\"{$col}\">\n" .
"{$valori}\n" .
"</textarea>" .
"
\n<input type=\"submit\" />\n" .
"</form>";
}
}
codice:
try{
$file = new dbFile('./public/file.txt');
if( isSet($_REQUEST['dbFile']) ): $file->salva() ;
else: echo $file->modifica();
endif;
}
catch(Exception $e){
echo 'Errore: ' . $e->getMessage() . '' ;
}
se qualcuno è interessato posso aggiungere dei commenti