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.
  • WildTurkey WildTurkey:
    is there a stephen green in the house?
    +1
  • The Helper The Helper:
    What is up WildTurkey?
  • The Helper The Helper:
    Looks like Google fixed whatever mistake that made the recipes on the site go crazy and we are no longer trending towards a recipe site lol - I don't care though because it motivated me to spend alot of time on the site improving it and at least now the content people are looking at is not stupid and embarrassing like it was when I first got back into this like 5 years ago.
  • The Helper The Helper:
    Plus - I have a pretty bad ass recipe collection now! That section of the site is 10 thousand times better than it was before
  • The Helper The Helper:
    We now have a web designer at my job. A legit talented professional! I am going to get him to redesign the site theme. It is time.
  • Varine Varine:
    I got one more day of community service and then I'm free from this nonsense! I polished a cop car today for a funeral or something I guess
  • Varine Varine:
    They also were digging threw old shit at the sheriff's office and I tried to get them to give me the old electronic stuff, but they said no. They can't give it to people because they might use it to impersonate a cop or break into their network or some shit? idk but it was a shame to see them take a whole bunch of radios and shit to get shredded and landfilled
  • The Helper The Helper:
    whatever at least you are free
  • Monovertex Monovertex:
    How are you all? :D
    +1
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top