0

i have a problem when inserting data into a text file, the data gets repeated & doesn't create newlines. this is my code:

<?php
$id = trim(strip_tags($_GET['id']));
$myfile = fopen("../../asset/Timeline/Logline.txt", "a") or die("file tidak ditemukan");
$tgl=date('d/m/Y');
$jam=date('H:i:s');
$slnmdl="select nama from $tabname where ID='$id'";
$result = mysqli_query($conn, $slnmdl);
$row = mysqli_fetch_assoc($result);
$nmdl = $row['nama'];
$log_content="$tgl|$jam|menghapus data $nmdl \n";
fwrite($myfile, $log_content);
fclose($myfile);
?>

viewer.php

<?php
$file_handle = fopen("Timeline/Logline.txt", "rb");

while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle);
    $parts = explode('|', $line_of_text);
    $lna=$parts[0];
    $lnb=$parts[1];
    $lnc=$parts[2];
    echo "$lna $lnb $lnc <br>";
}
fclose($file_handle);
?>

output

12/08/2022 14:00:59 menghapus data eWF5YW5n
12/08/2022 14:00:59 menghapus data

Logline.txt

12/08/2022|14:00:59| menghapus data eWF5YW5n 12/08/2022|14:00:59| menghapus data  

please help me find the fault

otw adoh
  • 11
  • 2
  • Welcome to Stack Overflow! Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating user provided values into the query. – Barmar Aug 12 '22 at 14:59
  • How are you viewing the file? What do you expect in the file? `\n` won't be rendered as new line in a browser. By `data gets duplicated` do you mean `menghapus data` appears twice, or both lines are double – user3783243 Aug 12 '22 at 15:00
  • I don't see any way this script could be doing that. Are you sure the log file was empty before the script ran? Are there any other scripts writing to the same log file? – Barmar Aug 12 '22 at 15:00
  • Also do you loop the fetch? This should only output 1 line as it currently is written – user3783243 Aug 12 '22 at 15:03
  • I'd probably do something like https://3v4l.org/u19RH for writing and then maybe https://3v4l.org/cPaNS for outputting logs. Might want to use PHP_EOL as well instead of `\n` to ensure using proper line endings – user3783243 Aug 12 '22 at 15:10
  • @user3783243 appears twice in one line – otw adoh Aug 12 '22 at 15:12

0 Answers0