PHP fwrite without duplicate - php

I want to write the code in such a way that, it will write and save any input in a .TXT file. Then there should be functions that will search the whole file (txt) if a text or word has been written or saved before, it should bring error.
If someone has written Love and another person wants to input Love again, it should bring an error message.
here is my code
<?php
$name=$_POST['name'];
$myfile=
fopen("man.txt" , "a+") or
die("Unable to open file!");
fwrite($myfile, "Name:".$name. "\r\n")
?>

Here I have used the in_array function to check an array we have populated ($users) for the submitted name.
If the name is found, is echos "Name Exists". If it is not found it echos "No" and adds the name.
<?php
$name = $_POST['name'];
if (empty($name)) { echo "Please enter your name"; } else $name=$name;
$myfile= fopen("mam.txt" , "a+") or die("Unable to open file!");
$path="mam.txt";
if (file_exists($path)) {
$contents = file_get_contents($path);
$contents = explode("\r\n", $contents);
$users = array();
foreach ($contents as $value) {
$users[] = $value;
}
// Search the file for the submitted name
if (in_array($name, $users)) {
// The name already exists
echo "Name exist";
} else {
// The name doesnt exist
echo "NO";
// Add the new name
fwrite($myfile, $name. "\r\n");
}
}
?>

Related

Check if value is in an array created from a txt file

I want to check if a value is in array created from a text file (a list of email addresses).
Why neither of these solutions work? (foreach or in_array)
(I've tried printing the array $text and it's ok, no problem coming from file.txt, same thing with $search)
$myfile = fopen("file.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$text[] = fgets($myfile);
}
fclose($myfile);
$search=$_POST['something'];
foreach ($text as $val) {
if (strpos($search, $val) !== FALSE) {
echo "oK";
}
}
/* OR * /
if (in_array($search, $text)) {
echo "OK"; }
Personally, I would not put an entire file input input into an array as its a waste of memory you're already using reading from a file (specially if its large).
You can instead do your "like" condition inside of the loop. I would use str_contains for ease if your PHP version supports it. Build an array based on found results.
if (!isset($_POST['something'])) die('Missing search term');
# TODO: Handle this Exception better
$emails = fopen("file.txt", "r") or die("Unable to open file");
$similarEmails = [];
while(!feof($emails))
if (str_contains(($line = fgets($emails)), $_POST['something']))
$similarEmails[] = $line;
fclose($emails);
References:
str_contains

PHP - How to write a line in text file if line already available in file then count the request

I want to write a PHP code which write a string line in text file if the line already available in text file then count the requests for example
text file contain:
red.apple:1
big.orange:1
green.banana:1
If some one request to add big.orange in file if its already available in file then count as big.orange:2 if not available then write new line big.orange:1
after execution code text file
red.apple:1
big.orange:2
green.banana:1
I've written the following code but not working.
<?PHP
$name = $_GET['fname']
$file = fopen('request.txt', "r+") or die("Unable to open file!");
if ($file) {
while (!feof($file)) {
$entry_array = explode(":",fgets($file));
if ($entry_array[0] == $name) {
$entry_array[1]==$entry_array[1]+1;
fwrite($file, $entry_array[1]);
}
}
fclose($file);
}
else{
fwrite($file, $name.":1"."\n");
fclose($file);
}
?>
Instead of creating your own format which you need to parse manually, you can simply use json.
Below is a suggestion about how it would work. It will add the requested fname value if it doesn't already exist and will also create the file if it doesn't already exists.
$name = $_GET['fname'] ?? null;
if (is_null($name)) {
// The fname query param is missing so we can't really continue
die('Got no name');
}
$file = 'request.json';
if (is_file($file)) {
// The file exists. Load it's content
$content = file_get_contents($file);
// Convert the contents (stringified json) to an array
$data = json_decode($content, true);
} else {
// The file does not extst. Create an empty array we can use
$data = [];
}
// Get the current value if it exists or start with 0
$currentValue = $data[$name] ?? 0;
// Set the new value
$data[$name] = $currentValue + 1;
// Convert the array to a stringified json object
$content = json_encode($data);
// Save the file
file_put_contents($file, $content);
If you still need to use this format (like, this is some exam test or legacy), try the function:
function touchFile($file, $string) {
if (!file_exists($file)) {
if (is_writable(dirname($file))) {
// create file (later)
$fileData = "";
} else {
throw new ErrorException("File '".$file."' doesn't exist and cannot be created");
}
} else $fileData = file_get_contents($file);
if (preg_match("#^".preg_quote($string).":(\d+)\n#m", $fileData, $args)) {
$fileData = str_replace($args[0], $string.":".(intval($args[1])+1)."\n", $fileData);
} else {
$fileData .= $string.":1\n";
}
if (file_put_contents($file, $fileData)) {
return true;
} else {
return false;
}
}

Validate Form Against a Text File

I have a simple form input box on my site that the user enters a 4 digit code into & submits. I need that code to match a list of codes in a text file. If not, it just returns an error. If so, it would execute another function. Using PHP.
I'm struggling on how to compare against that text file, seems simple to me...
I appreciate all of your help, learned SOOO much from SO.
Ian
Since you haven't provided a sample of your file or PHP code, am submitting the following:
Considering data.txt contains and with no commas from a .csv file, this will work.
1111
1112
1113
PHP
<?php
$search = "1111";
$file = "data.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
echo "$file DOES contains $search\n";
} else {
echo "$file does NOT contain $search\n";
}
This is another method which will work with or without a comma-seperated file:
1111,
1112,
1113,
PHP
<?php
$search = "1111";
$file = fopen("data.txt", "r") or die("Cannot open file!\n");
while ($line = fgets($file, 1024)) {
//if (preg_match("/\b1111\b/i", $line)) {
if (preg_match("/\b$search\b/i", $line)) {
echo "<b>Found match: " . $line . "</b>";
} else {
echo "No match: " . $line;
}
}
fclose($file);

Delete last line and check data in text file

I have the following code to write data to a text file.
$somecontent = "data|data1|data2|data3";
$filename = 'test.txt';
// Let's make sure the file exists and is writable first.
IF (IS_WRITABLE($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
IF (!$handle = FOPEN($filename, 'a')) {
PRINT "Cannot open file ($filename)";
EXIT;
}
// Write $somecontent to our opened file.
IF (!FWRITE($handle, $somecontent)) {
PRINT "Cannot write to file ($filename)";
EXIT;
}
PRINT "Success, wrote ($somecontent) to file ($filename)";
FCLOSE($handle);
} ELSE {
PRINT "The file $filename is not writable";
}
Now I want this text file to only every have 10 lines of data and when a new line of data is added which is unique to the other lines then the last line of data is deleted and a new line of data is added.
From research I have found the following code however total no idea how to implement it on the above code.
check for duplicate value in text file/array with php
and also what is the easiest way to implement the following code?
<?
$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($I=0;$i<count($inp)-1);$i++)
fwrite($out,$inp[$I]);
fclose($out)l
?>
Thanks for any help from a PHP newbie.
$file = fopen($filename, "r");
$names = array();
// Put the name part of each line in an array
while (!feof($file)) {
$line_data = explode("|", $fgets($file));
$names[] = $line_data[0]
}
$data_to_add = "name|image|price|link"
$data_name = "name" // I'm assuming you have this in a variable somewhere
// If the new data does not exist in the array
if(!in_array($data_name, $names)) {
unset($lines[9]); // delete the 10th line
array_unshift($lines, $data_to_add); // Put new data at the front of the array
// Write the new array to the file
file_put_contents($filename, implode("\n", $lines));
}

how to implement FILTER_SANITIZE_SPECIAL_CHARS

here's what I've got so far - i really need to ban any tags from being entered as it's like a guestbook, but this doesn't seem to work:
<?php
$txt = $_POST['txt'];
//the data
$data = "
$txt";
//my attempt to implement a filter
var_dump(filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS));
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
header('Location: http://www.google.com/');
?>
You need to assign the returned value of filter_var
$data = filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS);
filter_var can return FALSE if the filter fails. So, to be complete, you really should do something like:
$filtered_data = filter_var($data,FILTER_SANITIZE_SPECIAL_CHARS);
if($filtered_data !== FALSE) {
//write $filtered_data
} else {
//handle error
}

Categories