I have build this script that should save only unique lines, in this case url's. One url per line into a .txt file.
On my form I have only one value which is "url" from input name="url".
Script works, get's the value, checks if unique or not, writes into constant file , then I applied sorting from A to Z and writes sorted output into a new temp file. Here are my 3 things that I would like to ask for, any help appreciated:
I'm not sure if this is correct approach to write sorting into new file or is it possible to re-write the original file
Temp file is written with empty lines in between lines with values. Can't figure it out from where empty lines are coming from.
-
Last bit is that temp file is always one line less than constant file.
<?php // config $url = $_GET['url']; $n = " "; $data = $url . $n; $file = "datatest.txt"; // constant file $file2 = "datatest2.txt"; // temp file // check for duplicates & add new value if unique $unique_data = file_get_contents($file); if(strpos($unique_data, $data) === false){ $fh = fopen($file, 'a') or die("Can't open the file"); // chmod (optional) chmod($file,0666); chmod($file2,0666); // sort $lines = file($file); sort($lines); // write to original $record = file_put_contents($file, $data, FILE_APPEND | LOCK_EX); // write to temp $record2 = file_put_contents("$file2", implode(" ", $lines)); } // testing echo the results if (empty($record)){ echo "data already exists </br></br>"; }else{ echo $record . " bytes written to file </br></br>"; echo $record2 . " bytes written to file2 </br></br>"; } // display all (change file if needed) $fh = fopen($file, 'r'); $pageText = fread($fh, 25000); echo nl2br($pageText); ?>
Any input appreciated.
edit:
With @Barmar help I managed to eliminate points 2 & 3.
<?php
// config
$url = $_GET['url'];
$n = "
";
$data = $url . $n;
$file = "temp.txt"; // temp file in local folder
$file2 = "constant.txt"; // constant counterpart file
// check for duplicates & add new value if unique
$unique_data = file_get_contents($file);
if(strpos($unique_data, $data) === false){
$fh = fopen($file, 'a') or die("Can't open the file");
// chmod (optional)
chmod($file,0666);
chmod($file2,0666);
// write to original
$record = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
// sort
$lines = file($file, FILE_IGNORE_NEW_LINES);
sort($lines);
// write to temp
$record2 = file_put_contents($file2, implode("
", $lines), LOCK_EX);
}
// testing echo the results
if (empty($record)){
echo "data already exists </br></br>";
}else{
echo $record . " bytes written to file </br></br>";
echo $record2 . " bytes written to file2 </br></br>";
}
// display all (change file if needed)
$fh = fopen($file2, 'r');
$pageText = fread($fh, 25000);
echo nl2br($pageText);
?>
Still can't figure it out how to use only one file instead. @Barmar, I've tried to use your "in_array" but it's giving me an error.