I have a code:
$fp = fopen("/path/to/file", "w");
fwrite($fp, $var);
fclose($fp);
I need to do - add text string write in a text file without spaces with verification sample text.txt
foo
bar
foo_bar
If foo already exist in file - nothing to add.
Add a line of text in a file, but with check, if text is already there, example foo there is then nothing to add. If i add foofoo add it to text.txt
One way is to read into an array and check for the value. If it doesn't exist, append it (with a newline \n):
$lines = file("/path/to/file", FILE_IGNORE_NEW_LINES);
if(!in_array($var, $lines) {
file_put_contents("/path/to/file", "\n$var", FILE_APPEND);
}
Related
I would like to create a < input> where if someone enters text, a text file will add the content entered as a new row. I have tried highly modified the feature in this link: here
Just use the PHP_EOL (PHP end of line) constant that will create a new line.
This must be appended at the end of each line.
$file = fopen("myfile.txt", "a+");
fwrite($file, "hello".PHP_EOL);
// or...
fwrite($file, $myvar.PHP_EOL);
Alternatively, you could create your own, new, function:
function fwrite2($handle, string $string, $length = null, $newline = true) {
$string = $newline ? $string.PHP_EOL : $string;
if (isset($length)) {
fwrite($handle, $string, $length);
} else {
fwrite($handle, $string);
}
}
Call the above in the same manner, except the third argument will now create a new line automatically.
Edit following the comments:
The a+ means that the file is open and stored in $file and is available for reading and writing. The a stands for append; meaning the fwrite will append the file.
See more on the PHP documentation.
$file = fopen("myfile.txt", "a+");
fwrite2($file, "{$_GET['message']} | from {$_GET['sender']}");
Since you are using the URL to send data (ill-advised, but that is another point completely), you can access its contents through the superglobal variable - $_GET.
Notice that I have wrapped the values in curly braces. This is because $_GET is an array and if you want to interpolate arrays they must be wrapped, the same goes for class properties.
how can i add email in one by one using read/write in php
Am getting the following output and create one folder called "update" update folder contain user entered one email is stored and user enter another email id already existing email id replaced to new email id why?
I need one by one email id called
apap#gmail.com
asadsd#gmail.com
here are my code please review
<form action="demo.php" method="post">
<input type="text" name="textEmail">
<input type="submit" value="send">
</form>
Demo.php file are
<?php
// Open the text file
$f = fopen("update.txt", "w");
// Write text
$text = strtr(" ",' ', $_POST['textEmail']);
fwrite($f,$text);
//fwrite($f,$text);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("update.txt", "r");
// Read text
echo fgets($f);
fclose($f);
?>
Open the file in append mode instead of write mode
replace "w" with "a"
$f = fopen("update.txt", "a");
From: http://php.net/manual/en/function.fopen.php
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it...
Open your file as append mode so that you not need to open the file twice, for writing in the file, for you one email per line you need to use the \n after each email. For reading use the while loop to read end of the file and use fgets to make sure it reads the whole line at a time.
$myfile = fopen("update.txt", "a+");
$txt = $_POST['textEmail']."\n";
fwrite($myfile, $txt);
while(!feof($myfile)) {
echo fgets($myfile) . "<br/>";
}
fclose($myfile);
Documentation: php_file_create and php_file_open
I am unsure on what you are trying to achieve but I will clarify the difference between file write and file append.
Writing to a file when opened in 'w' mode writes from the current file pointer position which when open in 'w' mode is the very beginning of the file, to change this position in this mode use the fseek() method.
Writing to a file when opened in 'a' mode (append mode) will set the file pointer to the last location in the file and in php specifically will always when fwrite() is called will write to the end of the file.
Append File Example
Contents of update.txt before write:
sometext
sometext2
Code that writes to file
$f = fopen('update.txt', 'w');
//Description of 'a' mode from php manual
//Open for writing only; place the file pointer at the end of the file.
//If the file does not exist, attempt to create it. In this mode,
//fseek() has no effect, writes are always appended.
fwrite($f, "somevalue" . "\n");
fclose($f);
Results In an update.txt with contents:
sometext
sometext2
somevalue
Php doc on functions used in this example:
fopen()
fwrite()
<?php
if ($_POST['textEmail'] != '') {
$text = str_replace(" ", ' ', $_POST['textEmail']);
$pattern = '/([a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/';
preg_match_all($pattern,file_get_contents("update.txt"), $matches);
$emails = $matches[0]; // get Array of all email in file
if (!in_array($text, $emails)) { // echck for existing email
file_put_contents("update.txt", PHP_EOL.$_POST['textEmail'], FILE_APPEND);
}else{
echo 'Email address alerady exist';
}
echo $f = file_get_contents("update.txt");
}
?>
Would you please try this for demo.php ?
My colleague and I are working on a chat application for a small Flash based game. We would like to keep our chat file as small as possible by automatically deleting old text after the file has reached a certain limit. Say the file exceeds 50 lines, we would like to delete the existing information and begin again at line 1. Is this possible?
<?php
$file = "saved.txt";
$edited_text = $_POST['new_text'];
$open = fopen($file, "a+");
fwrite($open, "\n" . $edited_text);
fclose($open);
?>
Basically something like this:
$lines = file('saved.txt');
$lines[] = 'new line of text';
array_unshift($lines); // remove first array element
file_put_contents('saved.txt', implode(PHP_EOL, $lines));
Read the file into an array, one line per array element
Append your new line(s) of text
Remove as many lines from the start of the array as necessary
dump array back out to file as text.
This would work:
// Read entire file
$lines = file_get_contents('saved.txt');
// Add what you want to the beginning of array
array_unshift($lines, 'new line of text');
// Keep first 50 items
$lines = array_splice($lines, 0, 50);
// Write them back
file_put_contents('saved.txt', implode(PHP_EOL, $lines));
Will always keep the first 50 elements intact (which includes messages from new to old).
At first, I have a program which can read and add something on a text file. Now, what I want to do is to select all the data from database table and open, copy and replace and add something on the text file. It was just like I select all (ctrl+a) the content of the text file and then paste it but with added something.
$fileArray = file($filename);
//acl 10-0146-506_lp arp 00:15:af:a5:68:b1
$findthis = "#endofpart1\r\n";
$myKey = array_search($findthis,$fileArray);
array_splice($fileArray,$myKey,0,"acl ".$sn."_".$dd." arp ".$ma."\r\n");
//http_access allow 09-0651-410_cp
$findthis2 = "#endofpart2\r\n";
$myKey2 = array_search($findthis2,$fileArray);
array_splice($fileArray,$myKey2,0,"http_access allow ".$sn."_".$dd."\r\n");
$fp = fopen($filename,'w');
foreach($fileArray as $value) {
fwrite($fp,$value);
}
fclose($fp);
This code was the first program I did.
suppose I do have a text file with these lines
name: Mathew
Age : 32
Country : USA
Location : California
bla bla bla....
What I want is I want a php code which can read this file and display result to a webpage.
Use this code (untested):
$fp = fopen('filename.php');
while (!eof($fp)) {
$line = fgets($fp);
// Add code to display the values how you want
echo $line."<br>";
}
fclose($fp);
That will loop through the file line by line. Each line will be assigned to the $line variable, and then you can manipulate and display the values how you would like.
file() function reads a file into an array where one element represents a string in the file
Display the actual text or remove the name:, etc?
Use the file() function (tutorial?) to read the file in and then echo out / process each line.