www.webdeveloper.com
Results 1 to 14 of 14

Thread: Deleting lines in text file

Hybrid View

  1. #1
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54

    Deleting lines in text file

    Is this the proper way to do it?

    PHP Code:

    $fh 
    fopen($temp"w");
    $content = @file($file) or die ("Error...");
    foreach (
    $content as $line_num => $line) {
       if (!(
    preg_match("/\b$mailTo_User\b/i"$line))) {
          
    fwrite($fh"$line\n");
       }
    }
    copy($temp$file);
    fclose($fh);
    unlink($temp); 
    $temp and $file is assigned one file each (eg. myFile.tmp and myFile.txt).

    The script should delete the b@blip.com, but not ab@blip.com.

    I think it is working, is it?

    /Marcus

  2. #2
    Join Date
    Feb 2003
    Location
    Britain
    Posts
    1,335
    That looks great.

  3. #3
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    Well... the sad part is that it do not work.

    The temp-file is created, but it´s not copied to the original file after it´s filled.

    /Marcus

  4. #4
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    Please explain more clearly what it is that you need to do...

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

  5. #5
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    I have a file containing e-mailaddresses. This file shall be updated if someone want to add/remove his/hers e-mailaddress in the file.

    --- file ---
    mf22cs@student.hik.se
    marcus@farrington.nu
    ...
    --- end ---

    If userX try to add an address that is already in the file, it while generate an errormsg. And if userX try to remove an address that is not in the file, it while result in an errormsg.

    Well, I thought that I had solved it... but it seems to me that the driectory that I have my file in is accessed (at least the directory seems to been "touched").

    Wanna see the code? (some of the comments are in swedish)

    Code:
    	if ($alltOK) {
    		$file = "./temp/test";	// Filen som innehåller adresser.
    		$lock = $file . ".lock"; // Låsfilen som ev. låser upp användadet av "Filen".
    		$temp = $file . ".temp"; // Tempfilen som använd vid 
    		
    		$mailAdmin = "list-admin@skaraborg.nsf.scout.se";
    		$mailExtra = "From: list-admin@skaraborg.nsf.scout.se";
    		
    		if (!file_exists($lock)) {
    			// SKAPA LÅSFILEN
    			if (!copy($file,$lock)) die ("Ett internt fel har uppstått! Försök igen senare."); // Skapa låsfilen.
    			$notInFile = true;
    			// KONTROLLERA FILINNEHÅLL
    			$content = @file($file) or die ("Kunde inte öppna en för detta nödvändig fil...");
    	    	foreach ($content as $line_num => $line) {
    	      	if (preg_match("/\^$email$/i", $line)) {
    					$notInFile = false;
    	      	}
    	   	}
    			// LÄGG TILL I FILEN!
    			if ($action=="subcribe") {
    				if ($notInFile) {
    					$fh = fopen($file, "a");
    					flock($fh, 2);
    					fwrite($fh, "$email\n");
    					flock($fh, 3);
    					fclose($fh);
    					
    					// SKAPA MAIL TILL ADMIN					
    					$mailSubject = "$name har lagts till i e-postlistan";
    					$mailMsg = "$name från $group har med e-postadressen \"$email\" lagts till i e-postlistan.";
    					// SKICKA MAIL TILL ADMIN
    					mail($mailAdmin, $mailSubject, $mailMsg, $mailExtra);
    
    					// SKAPA MAIL TILL USER
    					$mailSubject = "Bekräftelse: Du har lagts till i vår e-postlista";
    					$mailMsg = "Detta är en bekräftelse på att du fortsättningsvis kommer att erhålla de ";
    					$mailMsg .= "meddelande som skickas till vår e-postlista.\n\nI din anmälan har följande";
    					$mailMsg .= " uppgifter skickats till vår listadministratör.\nDitt namn: $name\nDin kår: ";
    					$mailMsg .= "$group\nE-postadress: $_POST['epost']\n\nSkulle något vara felaktigt, kontakta ";
    					$mailMsg .= "oss.\n\nFör avanmälan, besök \"www.skaraborg.nsf.scout.se/epostlista.php\"\n\n";
    					$mailMsg .= "Med vänliga hälsningar\nlist-admin@skaraborg.nsf.scout.se";
    					// SKICKA MAIL TILL USER
    					mail($email, $mailSubject, $mailMsg, $mailExtra);
    			
    				} else {
    					mail($mailAdmin, "Tillägg", "Misslyckat", $mailExtra);
    				}
    			}
    	
    			// TA BORT UR FILEN!
    			else if ($action=="unsubcribe") {
    				if (!($notInFile)) {
    					// Skapa kod för att ta bort rader ut filen...
    					$fh = fopen($temp, "w");
    					$content = @file($file) or die ("Kunde inte öppna en för detta nödvändig fil...");
    			    	foreach ($content as $line_num => $line) {
    			      	if (!(preg_match("/\^$mailTo_User$/i", $line))) {
    							fwrite($fh, "$line\n");
    			      	}
    			   	}
    			   	fclose($fh);
    					copy($temp, $file);
    			   	unlink($temp);
    					
    					// SKAPA MAIL TILL ADMIN
    					$mailSubject_Admin = "$name har tagits bort i e-postlistan";
    					$mailMsg_Admin = "$name från $group har med e-postadressen \"$email\" tagits bort i e-postlistan.";
    					mail($mailAdmin, $mailSubject, $mailMsg, $mailExtra);
    					
    					// SKAPA MAIL TILL USER
    					$mailSubject = "Bekräftelse: Du har tagits bort i vår e-postlista";
    					$mailMsg = "Detta är en bekräftelse på att du fortsättningsvis inte kommer att erhålla de ";
    					$mailMsg .= "meddelande som skickas till vår e-postlista.\n\nI din avanmälan har följande";
    					$mailMsg .= " uppgifter skickats till vår listadministratör.\nDitt namn: $name\nDin kår: ";
    					$mailMsg .= "$group\nE-postadress: $_POST['epost']\n\nSkulle något vara felaktigt, kontakta ";
    					$mailMsg .= "oss.\n\nMed vänliga hälsningar\nlist-admin@skaraborg.nsf.scout.se";
    					
    					mail($email, $mailSubject, $mailMsg, $mailExtra);
    
    				} else {
    					mail($mailAdmin, "Borttagning", "Misslyckat", $mailExtra);
    				}
    			}
    			// TA BORT LÅSFILEN
    			unlink($lock);
    		}
    	}
    /Marcus

  6. #6
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    Tell me why you are using two text files, rather than just using one...

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

  7. #7
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    No reason at all... just me being

    /Marcus

  8. #8
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    Ok, if I get a chance, I'll get you some code... Might be a day or so...

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

  9. #9
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    Ok, this code will read from/write to a file called file.txt that is in the same directory as this script. You must CHMOD file.txt to 666

    PHP Code:
    <html>
    <head>
    <title>Add or Remove Email Addresses</title>
    <style type="text/css">
    a {
        color:darkblue;
    }
    </style>

    </head>
    <body>

    <form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="post">
    Email<input type="text" name="email" />
    Add <input type="radio" name="addremove" value="add" /> Remove <input type="radio" name="addremove" value="remove" />
    <input type="submit" name="submit" value="Submit" />
    </form>

    <?php

    $file 
    "file.txt"# IMPORTANT -- must CHMOD to 0666

    $search $_POST['email'];
    $x 0;
    $y 0;
    $addresstoremove "";
    $new_file "";

    if (
    $_POST['submit']) {

        
    $contents = @file($file) or die ("Failed to open <a href=\"$file\">$file</a>. Please be sure it is an absolute URL.");
        
        foreach (
    $contents as $line_num => $line) {
            if (
    preg_match("/^$search$/"$line)) {
                if (
    $_POST['addremove'] == "add") {
                    
    #email was alread in file -- can't add
                    
    echo "$search is already in the file";
                }
                else { 
    #remove was checked
                    
    $addresstoremove $line;
                    
    $y 1;
                }
                
    $x 1#a match was found
                
            
    }
            
    $new_file .= $line;
        }
        
        if (
    $y == 1) { #remove email from file
            
    $new_file preg_replace("/$addresstoremove/","",$new_file);
            
    $fp fopen ($file,"w");
            
    fwrite ($fp"$new_file");
            
    fclose ($fp);
            echo 
    "$addresstoremove was removed from the file.";
        }
        
        if (
    $x != 1) { #if a match was not found above
            
    if ($_POST['addremove'] == "add") {
                
    #add email to file
                
    $fp fopen ($file,"a");
                
    fwrite ($fp"\n$search");
                
    fclose ($fp);
                echo 
    "$search was added to the file.";
            }
            else { 
    #email was not in file to remove
                
    echo "$search was not found in the file.";
            }
        }
    }

    ?>

    </body>
    </html>

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

  10. #10
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    Thanks...

    and I hate to tell you that just 5 minutes before you submited your solution to my problem I solved it myself.

    But with at TEMP-file.

    Well, I think your solution is nicer... so I will change my code.

    /Marcus

  11. #11
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    lol... Glad to hear you kept working on it and didn't just sit around waiting for someone to give you an answer. But, as you see, there is no need to use a temp file... What you do is up to you...

    Cheers...

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

  12. #12
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    Last question:

    In the line:

    Code:
    if (preg_match("/^$search$/", $line)) {
    There are no additional chars missing, since [ php ] dropped a few / and \.

    Is there any good place to read about all the /^ and stuff used in a preg_match etc.

    /marcus

  13. #13
    Join Date
    Apr 2003
    Location
    Sweden
    Posts
    54
    Found one good site my self... www.php.net (in the Manual)...


  14. #14
    Join Date
    Dec 2002
    Location
    High on life
    Posts
    10,104
    Originally posted by mf22cs
    Last question:

    In the line:

    Code:
    if (preg_match("/^$search$/", $line)) {
    There are no additional chars missing, since [ php ] dropped a few / and \.
    Nope, that was it. The only thing you may want to do is make it case insensative, by adding an i after the last /... It's up to you...

    And yes, the manual is always a good place to look...

    Personal website http://www.ryanbrill.com/
    Business website: http://www.infinitywebdesign.com/
    TypeSpace http://www.typespace.org/

    I reject your reality and substitute it with my own!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles