How to check for duplicate content in txt file? - php

I have a .txt file which contains objects on each line.Meaning the first line is "baby",second line "toddler",next line "dog" and the line after is "cat".
I want to be able to add objects into my txt file using php but i want to prevent duplicates.Somehow my codes only work for "dog".When i try to add "dog" it will say this object already exist but when i try "cat" / "baby" /"toddler" it still adds even though it is already in the list.
CODES
$check = false;
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
$check = true;
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_lines = file('lbls/predefined_classes.txt');
foreach($file_lines as $line){
if($_POST['addLbl'] === $line){
$check = true;
}
}
if($check === false){
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
Txt File Content

because you add list manualy and have white space in the end of each line add trim() function solve problem
<?php
$check = false;
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
$check = true;
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_lines = file('lbls/predefined_classes.txt');
foreach($file_lines as $line){
if($_POST['addLbl'] === trim($line)){ // trim() added here
$check = true;
}
}
if($check === false){
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
}
?>
output test for cat :
The label cat already exists.

try the following, little shorter with same logic. No need for $check among other improvements.
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_str = file_get_contents('lbls/predefined_classes.txt');
if (!strrpos ( $file_str , $data)) { // not found
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
}

The $file_lines array looks like as below
array
(
[0] => \r\n
[1] => baby\r\n
[2] => toddler\r\n
[3] => cat\r\n
[4] => dog
)
You must remove next line escape sequence(i.e,\r\n) from $line and then compare with $_POST['addLbl']

You get lines with the new line character. Read the file and split it into lines.
$newline = PHP_EOL; // your editor might use another new line character
if(in_array($_POST['addLbl'], explode($newline, file_get_contents('test.txt'))))
// echo error message
else
// append to file
The entire task can be done in a few lines. Btw. check also for unset $_POST entries.
if(isset($_POST['add']))
{
if(!isset($_POST['addLbl']) || $_POST['addLbl'] === '')
echo ' Please enter a label';
elseif(in_array($_POST['addLbl'], explode(PHP_EOL, file_get_contents('lbls/predefined_classes.txt'))))
echo "The label {$_POST['addLbl']} already exists.";
elseif(false === file_put_contents('lbls/predefined_classes.txt',PHP_EOL . $_POST['addLbl'], FILE_APPEND | LOCK_EX))
echo ' Unable to add.An error occurred.';
else
{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}

Related

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>

if TXT empty echo message possible?

Hi I have a piece of code that is able to delete each newline in a txt file. Now my question is if the txt file is empty it gives an error message that $line doesn't exist. Now i want to add a piece off code that if txt has no content it echo's a message like "no emails in the list"
<?php
$delete = #$_GET['delete'];
$textFile = file("../emaillist/emaillist.txt");
$lines = count($textFile);
if($delete != "" && $delete >! $lines || $delete === '0') {
$textFile[$delete] = "";
$fileUpdate = fopen("../emaillist/emaillist.txt", "wb");
for($a=0; $a<$lines; $a++) {
fwrite($fileUpdate, $textFile[$a]);
}
fclose($fileUpdate);
echo"<p class='accept'>Contact verwijderd!</p>";
exit;
}
foreach($textFile as $key => $val) {
$pre= "<label style='float:left;' class='tablog3a'>";
$line = #$line . $pre . $val . "</label><a style='float:right;' href =?delete=$key><img class='clickreverse' src='images/deletetodo.png'></a><br>";
}
echo $line;
?>
I allready tried:
else {
echo "no emails in the list";
}
but that gave nothing....
I can think of a few ways to check if a file is empty:
$textfile = file('text.txt');
$lines = count($textfile);
if (empty($lines))
echo 'file is empty';
Or:
if (filesize('text.txt') === 0)
echo 'file is empty';
Or, if you want to check if it is empty, not including blank lines or extra whitespace:
$textfile = trim(file_get_contents('text.txt'));
if (empty($textfile))
echo 'file is empty';

php read and extract data from text file

This is to upload and print a text file. Now, this txt file contains details of people booking and comes via email and looks something like this:
some text (always the same)
= ================
text again
name : Mr F Someone
address: Somewhere
...
...
more same text
The problem is there are no delimiters. and I want to grab the data like "Mr", "F", "Someone",... and then put each one of them in an input field of a form. I tried something like this:
$section_a = file_get_contents($up_folder, NULL, NULL, 508, 2);
echo '<input type="text" name="Title" value="'.$section_a.'">';
but if it is "Miss" instead of "Mr" then it is a problem, same as the length of the name and so on. And there is more than one "booking" in a file. So, is there a way of getting the details of each booking out of the file to put each time in a form?
<?php
if($_FILES['userfile']['error'] > 0){
echo 'Houston, we have a problem: ';
switch($_FILES['userfile']['error'])
{
case 1: echo 'file too big'; break;
case 2: echo 'file too big'; break;
case 3: echo 'incomplete upload'; break;
case 4: echo 'uplad error'; break;
}
exit;
}
if($_FILES['userfile']['type'] != 'text/plain'){
echo 'Ooh noes! File is not plain text dude!';
exit;
}
$up_folder = 'upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
if(!move_uploaded_file($_FILES['userfile']['tmp_name'], $up_folder)){
echo 'cannot move file';
exit;
}
}
else{
echo 'error: ';
echo $_FILES['userfile']['name'];
exit;
}
echo 'file upload successful<br>';
$fp = fopen($up_folder, 'r');
$contents = fread($fp, filesize($up_folder));
fclose($fp);
$contents = strip_tags($contents);
$fp = fopen($upfile, 'w');
fwrite($fp, $contents);
fclose($fp);
echo 'Uploaded file content: <br> <br>';
echo $contents;
?>
$fetch = ['name','address'];
$output = [];
$fp = fopen($file, 'r');
while(!feof($fp) && count($output) !== count($fetch)) {
$line = fgets($line);
list($prefix, $value) = explode(':', $line, 2);
$prefix = strtolower(trim($prefix));
foreach($fetch as $f) {
if($prefix === $f) {
$output[$f] = trim($value);
break;
}
}
}
fclose($fp);
print_r($output);

why can't array_search find the value if the code of the key is "gb2312"?

my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}

A peculiar newbie debugging

It is one of the things I should have the know how but it really bugs. I have a large script which automates several tasks. It starts with uploading of files after which data from the files are extracted and then imported into mysql. In debugging mode it works perfectly but on my web front-end, execution stops after the data from the uploaded file is extracted. It never reaches the importation into database phase.
I realised that I had used this particular code below which I hold suspect:
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if($inFileName != "")
$inputFile = fopen($newFilePath,"r");
else exit(1);
if(!$inputFile)
exit(0);
while(!feof($inputFile)) {
It is obvious that the exit() as used terminates the scripts thereby leaving out the lines that is handling the import of data into mysql.WIth the above, the upload works and the data separation carried out but the import never got executed. After some study I reviewed that portion by doing something quite appropriate like:
if (file_exists($inFileName)){
$inputFile = fopen($newFilePath,"r");
}
else {
echo "No file found ";
}
if (is_readable($inputFile)){
echo " ";
}else {
echo 'The file could not be read';
}
Now this piece of code review did not get me anyway as the upload is not even possible.
Now my problem is to fix this little portion of the code so I get the other parts of the script after it to do the import. It has been a nightmare for a beginner like me. I would appreciate if someone could review the above portion in a different way. I hope to see something that is similar or different but valid. I have learnt tougher stuff than this but this is simply nuts. I hope someone could understand my explanation. Thanks
New Edit.
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
}
} else {
echo "File not accessable";
}
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
Entire Script
<?php
#This script has threee parts: The first handles the uploaded files while the second part retrieves all RMCs and Handover dates and the 3rd handles importation of the data into their respective table in mysql database.
# This part uploads text files
include 'setamainfunctions.php';
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
//echo count($_FILES['uploadedFile']['name'])." uploaded ";
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode("<br/>", $uploaded_files)."\n";
echo "</br>";
echo "<p> Please find the processed RMCs and corresponding handovers as text files named:outputRMCs.txt and OutputHandovers.txt in the Setapro project root folder</p>";
/* echo "<br/>";
echo "<br/>";
echo "<p> Result of Mobile GPRMCs Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and import mobile mobile GPRMCs successfuly completed";
echo "<br/>";
echo "<br/>";
echo "<p> Result of Handover Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and imports for mobile handovers successfuly completed";*/
}
# This is the start of a script which accepts the uploaded into another array of it own for extraction of GPRMCs and handover dates.
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
/*if(isset($_FILES['uploadedFile']['name']))
$_FILES['uploadedFile'] = '';
}else {
echo "yes";
}*/
$inFilesArray = ($_FILES['uploadedFile']['name']);
//$inFiles = fopen($_FILES['uploadedFile']['tmp_name'], 'r');
//This opens a textfile for writing operation and puts all the entries from the multiple text files into one distinct textfile
if( ($outFile4 = fopen("outputRMCs.txt", "a")) === false ){
echo " ";
}
$outFile5 = fopen("outputHandovers.txt", "a");
//processing individual files in the array called $inFilesArray via foreach loop
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
$correctFile = false;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
$correctFile = true;
}
}
if (!$correctFile)
echo "File not accessable";
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
//close the in files
fflush($outFile4);
fflush($outFile5);
}
fclose($outFile4);
fclose($outFile5);
#End of script for handling extraction
# This is the start of the script which imports the text file data into mysql database and does the necessary conversion.
$FilePath1 = $_SERVER["DOCUMENT_ROOT"] . '/setapro/outputRMCs.txt';
if (is_readable($FilePath1)) {
$handle = fopen($FilePath1, "r");
rmc_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#Begining of script to handle imports into handover table
$FilePath2 = $_SERVER["DOCUMENT_ROOT"].'/setapro/outputHandovers.txt';
if (is_readable($FilePath2)) {
$handle = fopen($FilePath2, "r");
mobile_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#End of script for handling imports into handover table
?>
It seems to me you want to do something more like this...
$newFilePath = $upload_directory."/".$inFileName;
$goodFile=false;
//Does the file exist?
if (file_exists($newFilePath)){
//If so, is it readable?
if (is_readable($newFilePath)){
//if it exists, and it readable, open it
$inputFile = file_get_contents($newFilePath);
//Don't display the error when done because file is good
$goodFile=true;
//Do Other stuff with file contents
}
}
if (!goodFile) echo "File Access Error";
You want to use newFilePath as it contains the path as well as the file name. The fact that you are checking for the file's existence and readability without also passing the file's path (only the file name) may be the cause of your issues.
UPDATE
try {
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') {
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
} catch (exception $e){
echo "General Error";
}

Categories