IT.COM

Help with PHP - Counting and Removing lines

Spaceship Spaceship
Watch
hey everyone...so here is what i'm trying to do.

I plan to setup a cron job which will run once every night. The cron will call a PHP file that should count the number of lines in a text file. Once the number of lines reaches X (for example, 75) it would then either remove the text file and recreate it - or just wipe the file clean and remove all 75 lines.

I'm not too good with PHP programming but I did find some code to count the number of lines. What i'm having problems with now would be the if statement that remove the file or the lines...Any help or links to a good tutorial would be nice!
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Last edited:
3
•••
Stack Overflow is a good source to learn PHP, then you'll code by hand (I did not code this by hand, just pieced it together to show you that it's a good source).

First, open the file to count the lines.
PHP:
$file="/path/to/your/file";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}

fclose($handle);
Source: http://stackoverflow.com/questions/...ting-the-number-of-lines-of-a-text-file-200mb

Then, determine if it's 75 lines and wipe:
PHP:
if($linecount >= 75) {
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, "");
fclose($fh);
}
Source: http://stackoverflow.com/questions/5650958/erase-all-data-from-txt-file-php
 
3
•••
Thanks for the links and sample code guys!! Gonna mess with this and test it out now :)
 
0
•••
Why not use a bash script ?
Here you go:

Code:
#!/bin/bash

filetocheck="/tmp/file.txt"

# count the lines
lines=$(wc -l "$filetocheck" | cut -d " " -f 1)
if [ "$lines" -ge 75 ]; then
    # delete the file
    rm -f "$filetocheck"
fi
If you have a very large file, PHP will takes ages to count the number of lines.
You have the shell command wc for this purpose. If you do:
Code:
wc -l /tmp/file.txt
You'll have something like this:
Code:
217 /tmp/file.txt
Hence the additional cut command.

-ge: greater than or equal
-gt: greater than
etc
 
1
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back