php delete a line awkward problem

alexho

New Member
Reaction score
0
Code:
function deleteline($filename,$liner) {

$xx = fopen ($filename, 'r');
$x=0;
while (!feof ($xx)) {
   $buffer = fgets($xx, 4096);
   
   if ($buffer!="" && $buffer!="\n") {
         //$buffer = str_ireplace("\n", "", $buffer);
      $faa[] = $buffer;
   }
   $x++;
}
$end=$x;

fclose ($xx);

$endr=$end-1;


$x=0;
while ($x<$end) {
   
   if ($faa[$x]!="" && $faa[$x]!="\n" && $x!=$liner) {
   
   //this hits right on heeheh
   
   //dno this works
   /*
   if ($x==$endr || $x>$endr) {
         $faa[$x] = str_ireplace("\n", "", $faa[$x]);
   }*/
echo "<$x>";
if ($x<$endr) {
      $saver.=$faa[$x];
} if ($x==$endr)  {
      $faa[$x] = str_ireplace("\n", "", $faa[$x]);
            $saver.=$faa[$x];
      }
      
      
   
   }
   $x++;
}


if ($end<1) {
die('hahaha');
}
//die("humm; $endr, ".$faa[$endr]);

$x=fopen($filename,"w");
fwrite($x,$saver);
fclose($x);
}
again im working with lines in files, this one never seems to work for things under 3 lines it adds a line to the top? most specifically the problem is with line 0, i can never delete that.. nevermind actually, it seems i have fixed it already...


Code:
function deleteline($filename,$liner) {
if ($liner<0) {
die('hahaha value is too small');
}

$x = fopen ($filename, 'r');
while (!feof ($x)) {
   $buffer = fgets($x, 4096);
   if ($buffer!="" && $buffer!="\n") {
      $faa[] = $buffer;
   }
}
fclose($x);

$x=0;
while ($x<count($faa)) {
if ($x!=$liner && $faa[$x]!="" && $faa[$x]!="\n") {
$excdel.=$faa[$x];
}
$x++;
}
$x=fopen($filename,"w");
fwrite($x,$excdel);
fclose($x);
}
must have been on crack when i wrote the other one
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
This code is wrong and will screw up things when many visitors are coming to that page.

Indeed, you are first reading in your whole content into an array (bad idea for large files) only to write it back afterwards, so imagine the following scenario:

  • User A and B request the page at the same time
  • the process handling request A is interrupted before executing fwrite($x,$saver);
  • the process handling request B starts its execution and is paused on line $x=0;
  • A continues its exection and writes to the file.
  • B resumes and writes its content to the file.

Outcome: congratulations, your file is empty.

Why? Because fopen(..., 'w') truncates the file, so B read in an empty file and processed it.

You have to implement file locking using flock(). For correct behaviour with an exclusive lock, open a second file $filename . '.lock' which makes sure B has to wait for A to finish (i.e. unlock the file) before it tries to open the file for reading.
 

alexho

New Member
Reaction score
0
how come it adds a break at the very end when i delete a line? it always happens for the end of a line in the file. this one doesnt work any better, so i suppose?
Code:
function cutline($filename,$line_no=-1) {

$strip_return=FALSE;

$data=file($filename);
$pipe=fopen($filename,'w');
$size=count($data);

if($line_no==-1) $skip=$size-1;
else $skip=$line_no-1;

for($line=0;$line<$size;$line++)
if($line!=$skip)
fputs($pipe,$data[$line]);
else
$strip_return=TRUE;

return $strip_return;
}
the flock will help with allowing 1 person to edit the file at a time, but the truncate with 'w' is my problem. In which way could i fix the addition of the extra space at the end use append?

Code:
$x=fopen($filename,"w");
if (flock($x, LOCK_EX)) {
fwrite($x,$saver);
flock($x, LOCK_UN);
} else {
    echo "<script>alert('please wait.');</script>";
}
fclose($x);
^^ would lock and unlock correct?

would be put around the fwrite and solve a part of a problem
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
^^ would lock and unlock correct?

would be put around the fwrite and solve a part of a problem

No, putting it there is useless. You have to get your exclusive at the moment you read the data and release if after you're done writing it back, so:
  • either open your file for read/write, lock it prior to calling fread/fgets and unlock it after completing your write
  • or use a second file, which only servers the purpose of locking, while you leave your code as-is.
    1. get an exclusive lock on myfile.txt.lock
    2. open myfile.txt for reading
    3. read from myfile.txt
    4. close myfile.txt
    5. open myfile.txt for writing
    6. write to myfile.txt
    7. close myfile.txt
    8. release the lock on myfile.txt.lock
 

alexho

New Member
Reaction score
0
Code:
function deleteline($filename,$liner) {
$z = fopen ($filename.lock, 'r');
flock($z, LOCK_EX);

if ($liner<0) {
die('the value is too small.');
}
$xx = fopen ($filename, 'r');
$x=0;
while (!feof ($xx)) {
   $buffer = fgets($xx, 4096);
   if ($buffer!="" && $buffer!="\n") {
         //$buffer = str_ireplace("\n", "", $buffer);
      $faa[] = $buffer;
   }
   $x++;
}
$end=$x;
fclose ($xx);
if ($end<0) {
die('the value is too small #2.');
}
$endr=$end-1;

$x=0;
while ($x<$end) {
   
   if ($faa[$x]!="" && $faa[$x]!="\n" && $x!=$liner) {
if ($x<$endr) {
      $saver.=$faa[$x];
} if ($x==$endr)  {
      $faa[$x] = str_ireplace("\n", "", $faa[$x]);
            $saver.=$faa[$x];
      }
   }
   $x++;
}

$x=fopen($filename,"w");
fwrite($x,$saver);
fclose($x);

flock($z, LOCK_UN);
fclose($z);
}
my code then is wrong anyway for what i'm trying to do anyway i do not want it leaving an empty space after "w" which it does anyway if i delete the last line and try to append to it it leaves an open space before the new append.
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
What about this one?
PHP:
<?php

function removeLastLineOfFile($filename)
{
	if (!is_resource($fh = fopen($filename, 'r+')))
	{
		return false;
	}

	if (!flock($fh, LOCK_EX))
	{
		fclose($fh);
		return false;
	}

	$cur_pos = 0;
	$truncate_at = 0;
	while(fgets($fh) !== false)
	{
		$truncate_at = $cur_pos;
		$cur_pos = ftell($fh);
	}

	if (!feof($fh))
	{
		flock($fh, LOCK_UN);
		fclose($fh);
		return false;
	}

	if ($truncate_at > 0)
	{
		ftruncate($fh, $truncate_at);
	}

	flock($fh, LOCK_UN);
	fclose($fh);

	return true;
}

?>

To test it:
PHP:
removeLastLineOfFile('my_test_file.txt');
 

alexho

New Member
Reaction score
0
Code:
     $fp = fopen("test.txt", "w");
    if (flock($fp, LOCK_EX)) {
        echo "Got lock!\n";
        sleep(10);
        flock($fp, LOCK_UN);
    } else {
        print "Could not get lock!\n";
    }
fclose($fp);
^ seems to work between sleep time i cannot open the file it is locked i could put anything to manipulate the file and it would work.


And for your removeLastLineOfFile('file.txt'); function, what i meant was modifying the deleteline() function i had. And if it was possible so that it it could be made to work taking into account so that the last line for when i write everything without the delete wouldnt add an extra line at the end, because when things are appended it has a nasty line break.

Code:
example:
file:
0 apples
1 bananas
2 oranges
3 tomatoes

i want to rid the tomatoes from this file using deleteline("test.txt",3); this would then filter the 3rd line out, leaving a file with no hanging leftover \n's
so it would then be

0 apples
1 bananas
2 oranges

and done with deleteline("test.txt",0); yeild the same with 'no extra lines of nothing'.
0 bananas
1 oranges
2 tomatoes
sorry if i wasn't clear :(
the flock would then be useful with the 'w' in this function i use, if i can get it to work.
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Here's a generic filter function then, using an external lock file and two file handlers for concurrent reading and writing on the file:

PHP:
<?php

function deleteLineFromFile($filename, $regexp)
{
	$lock_filename = '.' . $filename . '.lock';
	
	if (!is_resource($lh = fopen($lock_filename, 'w')))
	{
		return false;
	}

	flock($lh, LOCK_EX);

	if (!is_resource($rh = fopen($filename, 'r')))
	{
		flock($lh, LOCK_UN);
		fclose($lh);
		unlink($lock_filename);
		return false;
	}

	if (!is_resource($wh = fopen($filename, 'r+')))
	{
		fclose($rh);
		flock($lh, LOCK_UN);
		fclose($lh);
		unlink($lock_filename);
		return false;
	}

	$rpos = 0;
	$wpos = 0;

	while(($line = fgets($rh)))
	{
		$bytes = ftell($rh) - $rpos;

		if (!preg_match($regexp, $line))
		{
			if ($rpos != $wpos)
			{
				fputs($wh, $line);
			}
			else
			{
				fseek($wh, $bytes, SEEK_CUR);
			}

			$wpos += $bytes;
		}

		$rpos += $bytes;
	}

	if (($rv = feof($rh)))
	{
		ftruncate($wh, $wpos);
	}

	fclose($rh);
	fclose($wh);

	flock($lh, LOCK_UN);
	fclose($lh);
	unlink($lock_filename);

	return $rv;
}

?>

Example use:
PHP:
deleteLineFromFile('test', '/^1/')


EDIT: note that you can reduce the above parser code through a one-liner, if you can afford storing the whole content of the file in memory. :D
(You'd better do some error checking on the one-liner thou).

PHP:
<?php

function deleteLineFromFile2($filename, $regexp)
{
	$lock_filename = '.' . $filename . '.lock';
	
	if (!is_resource($lh = fopen($lock_filename, 'w')))
	{
		return false;
	}

	flock($lh, LOCK_EX);

	file_put_contents($filename, implode("\n", preg_grep($regexp, file($filename))));

	flock($lh, LOCK_UN);
	fclose($lh);
	unlink($lock_filename);

	return true;
}

?>
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top