Nubcake
Nubcake

Reputation: 397

Update string in file

I have a file with information like this:

    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name  
    IP=127.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name  
    IP=121.0.0.1 Status=On Name=Name 
    IP=121.0.0.1 Status=On Name=Name

How would I update the information in this file? E.g how would I update the row with the localhost IP set Status to Off and Name to test etc. What I tried is to locate the row I want to modify by IP address (in this case localhost - 127.0.0.1) then replace the value of Status= to Off with str_replace() etc. But when I try to change it back to On again it writes over another line/makes an empty line/adds more info.

Code I tried:

<?php
$file = fopen('user_info.wrd','r+');
while (!feof($file))
 {
  $str=fgets($file);
  if (strstr($str,$_SERVER['REMOTE_ADDR'])) 
    {
     $Status=substr($str,strpos($str,'Status=')+7);
     $Status=substr($Status,0,strpos($Status,' '));
     fseek($file,(ftell($file)-strlen($str)));
     $str=str_replace($Status,'Off',$str);
     echo $str;
     $str=trim($str);
     fwrite($file,$str);
     fclose($file);
     die;
    }
 }  
?>

Upvotes: 0

Views: 141

Answers (1)

stefreak
stefreak

Reputation: 1450

Here are my versions of the read_file and write_file functions (the code is not tested, but should work).

function read_file($filename) {
  $contents = file_get_contents($filename);
  $lines = explode((strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "\r\n" : "\n"), $contents);
  $data = array();
  foreach($lines as $line) {
    $fields = explode(" ", $line);
    $ip_address = null;
    foreach($fields as $field) {
      $keyvaluepair = explode('=', $field);
      if ($keyvaluepair[0] === 'IP') {
        $ip_address = $keyvaluepair[1];
        $data[$ip_address] = array();
      } else {
        $data[$ip_address][$keyvaluepair[0]] = $keyvaluepair[1];
      }
    }
  }
  return $data;
}

function write_file($filename, $array) {
  $data = '';

  foreach($array as $ip_address => $flags) {
    $data .= "IP={$ip_address} Status={$flags['Status']} Name={$flags['Name']}";
    $data .= (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "\r\n" : "\n");
  }

  file_put_contents($filename, $data);
}

Usage:

$data = read_file('filename');
$data['127.0.0.1']['Status'] = 'Off';
$data['127.0.0.1']['Name'] = 'My_Fancy_Name'; // note that spaces in the name are not allowed!
write_file('filename', $data);

Upvotes: 1

Related Questions