View Single Post
Old 09-13-2007, 08:39 AM   #2 (permalink)
jordie
The Wanderer
 
Join Date: Sep 2007
Location: Sydney, Australia
Posts: 19
Thanks: 0
jordie is on a distinguished road
Default

I suppose you could use PHP's file() function which reads in a file into an array with each line being a new element of the array.

PHP Code:
$file_array file('/home/mypath/file.txt');

foreach (
$file_array as $line => $value) {
    echo 
$value "<a href='url'>Delete</a><br />\n";

To be honest I would recommend using a database rather than this. Because the only way I can see here would be to delete the items based upon their line number or value. Both present issues. If you use the line number and someone else has edited the file in between the time you loaded the page and clicked delete, you could end up deleting a different line. The value could also potentially not be unique, so selecting to delete a line that has another the same would result in them both being deleted, though I think this one is your safer bet.

So overall, what you could do is this:

PHP Code:
$file_name '/home/mypath/file.txt';

// this reads the file into an array
$file_array file($file_name);

if(
$_GET['action'] == 'deleteline'){
    
// a delete request was made, unencode the data
    
$delete_value base64_decode($_GET['line']);

    
// loop through the file array and only include
    // the lines that aren't the one we want to delete into
    // a  new array
    
foreach ($file_array as $line => $value) {
        if(
$delete_value != $value){
            
$new_array[] = $value;
        }
    }
    
// replace the old array with our new one with a
    // line removed
    
$file_array $new_array;
    
    
// collapse the array to a string
    
$file_data implode('',$file_array);

    
// write the data back to the file
    
$handle fopen($file_name'w+');
    
fwrite($handle$file_data);
    
fclose($handle);
}

reset($file_array);

foreach (
$file_array as $line => $value) {
    echo 
$value "<a href='".$_SERVER['PHP_SELF']."?action=deleteline&line=".base64_encode($value)."'>Delete</a><br />\n";

jordie is offline  
Reply With Quote