Monday, September 21, 2009

File Handling in php Through Class

class File{
private $fileName;
private $fileMode;
private $filePointer;
private $fileSize;

public function File($fileName='',$fileMode='',$fileSize=''){
//echo "
Construcor Call
";
if(!empty($fileName))
$this->fileName=$fileName;
if(!empty($fileMode))
$this->fileMode=$fileMode;
if(empty($fileSize))
$this->fileSize=filesize($this->fileName);
else
$this->fileSize=$fileSize;
}
function FileDetail(){

echo "
fileName[$this->fileName] fileMode[$this->fileMode][$this->filePointer] fileSize[$this->fileSize]
";
}
function FileExists($fileName){
if(!file_exists($fileName)){
echo "Error: This file does not exist!";
exit();
}
}
public function OpenFile(){

if(!$this->filePointer=fopen($this->fileName,$this->fileMode)){
echo "Cannot open file ($this->fileName)";
exit;
}

}
public function CloseFile(){
fclose($this->filePointer);
}
public function CheckFileMode($fileMode){
}
public function SetNameSize($fileName='',$fileSize=''){

if(!empty($fileName))
$this->fileName=$fileName;
if(empty($fileSize))
$this->fileSize=filesize($this->fileName);
else if(gettype($fileSize)=='integer')
$this->fileSize=$fileSize;
else {
echo "Erro:Invalid File Size only use Integer value!";
exit();
}

}
function SetStringSize($string){
$this->fileSize=strlen($string);

}
public function SetMode($fileMode){

$this->fileMode=$fileMode;
}


public function ReadFile($fileName='',$fileSize=''){
$this->FileExists($fileName);
$this->SetNameSize($fileName,$fileSize);

$this->SetMode('r');
$this->OpenFile();
if($this->fileSize>0)
return fread($this->filePointer,$this->fileSize);
else
return fread($this->filePointer);

}
public function WriteFile($fileName,$content,$fileSize='',$fileMode='w'){
$this->FileExists($fileName);
$this->SetNameSize($fileName,$fileSize);
if(empty($fileSize))
$this->SetStringSize($content);
$this->SetMode($fileMode);
$this->OpenFile();
if($this->fileSize>0)
return fwrite($this->filePointer,$content,$this->fileSize);
else
return fwrite($this->filePointer,$content);

}
public function SearchFile($fileName,$content){
return strpos($this->ReadFile($fileName),$content);
}
function AppendFile($fileName,$content){
$this->FileExists($fileName);
$this->SetNameSize($fileName);
$this->SetMode('a');
$this->OpenFile();
if($this->fileSize>0)
return fwrite($this->filePointer,$content,$this->fileSize);
else
return fwrite($this->filePointer,$content);
}
function ReplaceFile($fileName,$search,$replace){
return $this->WriteFile($fileName,str_replace($search, $replace,$this->ReadFile($fileName)));

}

}
?>
//Class Test
$file=new File();
echo $file->ReadFile('test.txt);
//$file->WriteFile('test.txt','this is new text in this file the quick brown fox jumpso over the lazy dog');
//echo $file->SearchFile('test.txt','love')
//$file->AppendFile('test.txt','rajput');
//$file->ReplaceFile('test.txt','rajput','change');
?>