Advertisement
Guest User

Untitled

a guest
Oct 21st, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. function delLineFromFile($fileName, $lineNum){
  2. // check the file exists
  3. if(!is_writable("chat.txt"))
  4. {
  5. // print an error
  6. print "The file chat.txt is not writable";
  7. // exit the function
  8. exit;
  9. }
  10. else
  11. {
  12. // read the file into an array
  13. $arr = file("chat.txt");
  14. }
  15.  
  16. // the line to delete is the line number minus 1, because arrays begin at zero
  17. $lineToDelete = $lineNum-1;
  18.  
  19. // check if the line to delete is greater than the length of the file
  20. if($lineToDelete > sizeof($arr))
  21. {
  22. // print an error
  23. print "You have chosen a line number, <b>[$lineNum]</b>, higher than the length of the file.";
  24. // exit the function
  25. exit;
  26. }
  27.  
  28. //remove the line
  29. unset($arr["$lineToDelete"]);
  30.  
  31. // open the file for reading
  32. if (!$fp = fopen("chat.txt", 'w+'))
  33. {
  34. // print an error
  35. print "Cannot open file (chat.txt)";
  36. // exit the function
  37. exit;
  38. }
  39.  
  40. // if $fp is valid
  41. if($fp)
  42. {
  43. // write the array to the file
  44. foreach($arr as $line) { fwrite($fp,$line); }
  45.  
  46. // close the file
  47. fclose($fp);
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement