Read And Write From a File Line by Line in PHP

Hello Friends,
This is a simple example which demonstrates how one can write into a file line by line data in json format and read from that file again line by line.

1. Create a file index.php and write the following code there.
require_once(‘db.php’);

$db=new db();

$db->insert(“insert into tablename values(‘sudhanshu’, ’22’, ‘male’)”);
$result=$db->readandexecute();
if($result){
    foreach($result AS $k => $re){
        if($k!=” && $re!=”){
        echo “

".$k.' :: '.$re."

“;
        }
    }
}else{
    echo ‘na’;
}

2. Create a file db.php

class db{
 public function insert($query){
              $this->filestore($query);
 }
 private function filestore($q, $qstatus=true){
              global $profiler;
              $arr=explode(‘ ‘, trim($q));
              $getfirst=strtolower($arr[0]);
              $gethird=strtolower($arr[2]);
             
              if($getfirst==’show’ || $getfirst==’select’ || $gethird==’errorlog’){
                  return false;
              }
              if($qstatus==true){
              $filedir=’.’.’\\’.’dblogs’;
              $filename=’log.txt’;
              $fileaddress=$filedir.’\\’.$filename;
              $query[‘id’]=uniqid();
              $query[‘query’]=$q;
              $query[‘status’]=’unsynchronized’;
             
              if(!file_exists($filedir)) //part A
              {
                    mkdir($filedir);//directory created
              }
              if(!file_exists($fileaddress)){
                  $fhandle= fopen($fileaddress,’a’);
                  fclose($fhandle);
              }
                  // Let’s make sure the file exists and is writable first.
              if (is_writable($fileaddress)) {
               $profiler->add(‘Now Storing the queries in File[‘.$fileaddress.’]’);
                      // The file pointer is at the bottom of the file hence
                      // that’s where $filecontent will go when we fwrite() it.
                        if (!$handle = fopen($fileaddress, ‘a’)) {
                        echo “Cannot open file (“.$fileaddress.”)”;
                        return FALSE;
                        }
                 
                         // Write $filecontent which is of array type and stored in $vals to our opened file.
                         if (fwrite($handle, json_encode($query).”\r\n”) === FALSE) {
                        // echo “Cannot write to file ($fileaddress)”;
                         }
                         fclose($handle);
                         $profiler->add(‘Error Stored in File[‘.$fileaddress.’]’);
                         return TRUE;
                  }
                   $profiler->add(‘File [‘.$fileaddress.’] not found.’);
        return FALSE;
              }
    }
 public function readandexecute(){
              return $this->getqueriesfromfile();
      }
      public function getqueriesfromfile(){
              $filedir=’.’.’\\’.’dblogs’;
              $filename=’log.txt’;
              $fileaddress=$filedir.’\\’.$filename;
              $matches=array();
             
                $file = fopen($fileaddress, “r”);
                //Output a line of the file until the end is reached
                while(!feof($file))
                {
                    $lines=fgets($file);
                    $jsonarray=json_decode($lines, true);
                    if($jsonarray[‘status’]!=’synchronized’){
                        $matches[$jsonarray[‘id’]]=$jsonarray[‘query’];
                       // fputs($file, json_encode(array(‘id’=>$jsonarray[‘id’])))
                    }
   
                }
                fclose($file);
                return $matches;
      }
}