I need your help.
I need to every time the code stores the information in txt file, then each new record to the new line and what should be done to all be numbered?
<?php
$txt = "data.txt";
if (isset($_POST['Password'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['Password'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
Added some comments to explain the changes.
<?php
$file = "data.txt"; // check if both fields are set
$fh = fopen($file, 'a+'); //open the file for reading, writing and put the pointer at the end of file.
$word=md5(rand(1,10)); //random word generator for testing
fwrite($fh,$word."\n"); // Write information to the file add a new line to the end of the word.
rewind($fh); //return the pointer to the start of the text file.
$lines = explode("\n",trim(fread($fh, filesize($file)))); // create an array of lines.
foreach($lines as $key=>$line){ // iterate over each line.
echo $key." : ".$line."<br>";
}
fclose($fh); // Close the file
?>
PHP
fopen
fread
explode
You can do like this in a more simpler way..
<?php
$txt = "data.txt";
if (isset($_POST['Password']) && file_exists($txt))
{
file_put_contents($txt,$_POST['Password'],FILE_APPEND);
}
?>
we open file to write into it ,you must make handle to a+ like php doc
So your code will be :
<?php
$fileName = "data.txt"; // change variable name to file name
if (isset($_POST['Password'])) { // check if both fields are set
$file = fopen($fileName, 'a+'); // set handler to a+
$txt=$_POST['Password'];
fwrite($file,$txt); // Write information to the file
fclose($file); // Close the file
}
?>
Related
I have a php script for userinput and now I would like this script to "add to existing file data.txt (preferred)" or make a seperate file for each answer named $field1
<?php
$txt = "data.txt";
$fh = fopen($txt, 'w+');
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$txt=$_POST['field1'].' - '.$_POST['field2'];
file_put_contents('data.txt',$txt."\n",FILE_APPEND); //log to data.txt
exit();
}
fwrite($fh,$txt); // write information to the file
fclose($fh); // close the file
?>
It's a form on the website that has to write
"Name - Vote"
"Name - Vote"
"Name - Vote"
Right now it overrides the file instead of adding to it
#Eric: Read the comments inserted in the code for resolution
<?php
$txt = "data.txt";
$fh = fopen($txt, 'a'); // the correct open flag for append end of file
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh, $txt . "\n"); // carriage return added (*assumption needed)
// exit(); // omit
}
// fwrite($fh,$txt); // write information to the file // pointless, redundant
fclose($fh); // close the file
?>
This is the code I've figured out.
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$json = '{"username":"'.$username.'",'.'"email":"'.$email.'"}';
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>
But this is absolutely not the right way.
If your $_POST array has all of the data you need you can encode it as JSON and write to a file:
<?php
$json = json_encode($_POST);
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>
If you want to append to the file you will need to read the file into an array first, add the newer parts of the array then encode it again before writing back to the file just like my friend #Rizier123 describes.
Okay, I found a more efficient way to do this.
Original Answer
// read the file if present
$handle = #fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
Without decoding the whole JSON file into the arrays.
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));
}
Is it possible for me to read from / and write to the same file? If so, could you explain me
how to do that
Yes it is.
$file = "./test.txt";
// open file at the beginning.
$fh = fopen($file, 'r+');
//read the first line of the file. (advances pointer to the second line).
$contents = fread($fh);
// modify contents.
$new_contents = str_replace("hello world", "hello", $contents);
// make sure you're back at the 0 index.
fseek( $file, 0 );
// write
fwrite($fh, $new_contents);
// close.
fclose($fh);
// done!
In PHP 5 file_put_contents is the easiest way:
<?php
$file = 'people.txt';
$current = file_get_contents($file); // Open the file to get existing content
$current .= "John Smith\n"; // Append a new person to the file
file_put_contents($file, $current); // Write the contents back to the file
?>
file_put_contents("write.txt",file_get_contents("read.txt"));
Here is some documentation. You can see there all the parameters you can use in these functions.
http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fread.php
http://www.php.net/manual/en/function.fclose.php
http://www.php.net/manual/en/function.fwrite.php
http://www.php.net/manual/en/function.fseek.php
I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>