1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
<?
class FileModifier
{
var $openMode;
var $lastMessage;
function FileModifier()
{
$this->openMode = "w"; // open for read / writing text
}
function ModifyFile($fileName, $primaryKeyValue, $newEntry)
{
$my_ftp_context = stream_context_create(array('ftp' => array('resume_pos' => TRUE)));
//$fd=fopen($file, 'w', FALSE, $my_ftp_context);
$this->lastMessage = '';
$fp = fopen($fileName,$this->openMode,0, $my_ftp_context);
if ($fp == null)
{
$this->lastMessage = 'Error opening file for read / write.';
return false;
}
$fileSize = filesize($fileName);
$fileContent = fread($fp, $fileSize); // read file
if (strlen($fileContent) > 0) // if not empty content;
{
$pattern = '/('.$primaryKeyValue.'\s*=>\s*\d+,\d+,).+/i'; // regex pattern to search for the given key
$replacement = '${1}'.$newEntry; // replacement string
$newFileContent = preg_replace($pattern, $replacement, $fileContent); // replace the content
if ($newFileContent != $fileContent) // if replacement was made
{
fseek($fp, SEEK_SET); // move pointer to begining of file
fwrite($fp, $newFileContent); // write new content
$this->lastMessage = 'File was modified.'; // if key didn't exists
}
else
$this->lastMessage = 'Key was not found.'; // if key didn't exists
}
else
$this->lastMessage = 'File content empty.';
fclose($fp); // close the file pointer
return true;
}
function GetLastMessage() { return $this->lastMessage; }
}
?> |
Partager