A registration form write the data to a txt file using this code:
<?
if( isset( $_GET['list'] ) AND $_GET['list'] != '' ) {
$listId = $_GET['list'];
}
$email = $_POST['widget-subscribe-form-email'];
$fname = isset( $_POST['widget-subscribe-form-fname'] ) ? $_POST['widget-subscribe-form-fname'] : '';
$lname = isset( $_POST['widget-subscribe-form-lname'] ) ? $_POST['widget-subscribe-form-lname'] : '';
$fp = fopen("newsletter_subscriptions.txt","w+");
fputs($fp, "email : ");
fputs($fp, $_POST['widget-subscribe-form-email']);
fputs($fp, "\nPrénom : ");
fputs($fp, $_POST['widget-subscribe-form-fname']);
fputs($fp, "\nNom : ");
fputs($fp, $_POST['widget-subscribe-form-lname']);
fclose($fp);
?>
My problem is that each new record erase the previous one. I want to keep all records in the txt file.
How to do it ?
File open modes:
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 reading and writing; place the file pointer at the end of the file.
You are opening the file in the wrong mode. From the manual:
'w+' Open for reading and writing; 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.
You want to append to the file, you should use:
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
Change the fopen line to:
$fp = fopen("newsletter_subscriptions.txt","a+");
Related
I'm trying to make a download counter in a website for a video game in PHP, but for some reason, instead of incrementing the contents of the downloadcount.txt file by 1, it takes the number, increments it, and appends it to the end of the file. How could I just make it replace the file contents instead of appending it?
Here's the source:
<?php
ob_start();
$newURL = 'versions/v1.0.0aplha/Dungeon1UP.zip';
//header('Location: '.$newURL);
//increment download counter
$file = fopen("downloadcount.txt", "w+") or die("Unable to open file!");
$content = fread($file,filesize("downloadcount.txt"));
echo $content;
$output = (int) $content + 1;
//$output = 'test';
fwrite($file, $output);
fclose($file);
ob_end_flush();
?>
The number in the file is supposed to increase by one every time, but instead, it gives me numbers like this: 101110121011101310111012101110149.2233720368548E+189.2233720368548E+189.2233720368548E+18
As correctly pointed out in one of the comments, for your specific case you can use fseek ( $file, 0 ) right before writing, such as:
fseek ( $file, 0 );
fwrite($file, $output);
Or even simpler you can rewind($file) before writing, this will ensure that the next write happens at byte 0 - ie the start of the file.
The reason why the file gets appended it is because you're opening the file in append and truncate mode, that is "w+". You have to open it in readwrite mode in case you do not want to reset the contents, just "r+" on your fopen, such as:
fopen("downloadcount.txt", "r+")
Just make sure the file exists before writing!
Please see fopen modes here:
https://www.php.net/manual/en/function.fopen.php
And working code here:
https://bpaste.net/show/iasj
It will be much simpler to use file_get_contents/file_put_contents:
// update with more precise path to file:
$content = file_get_contents(__DIR__ . "/downloadcount.txt");
echo $content;
$output = (int) $content + 1;
// by default `file_put_contents` overwrites file content
file_put_contents(__DIR__ . "/downloadcount.txt", $output);
That appending should just be a typecasting problem, but I would not encourage you to handle counts the file way. In order to count the number of downloads for a file, it's better to make a database update of a row using transactions to handle concurrency properly, as doing it the file way could compromise accuracy.
You can get the content, check if the file has data. If not initialise to 0 and then just replace the content.
$fileContent = file_get_contents("downloadcount.txt");
$content = (!empty($fileContent) ? $fileContent : 0);
$content++;
file_put_contents('downloadcount.txt', $content);
Check $str or directly content inside the file
I want to add a value (not overwrite!) to a txt file with file_put_contents
This is what i have so far:
$fileUserId = fopen("fileUserId.txt", "w") or die("Unable to open file!");
$UserIdtxt = $UserID."||";
file_put_contents("fileUserId.txt", $UserIdtxt, FILE_APPEND);
fclose($fileUserId);
$UserID is an integer, like 1, 2, 3 etc.
So when the the UserID is 1, the fileUserId.txt looks like this:
1||
When there is another user with ID 2,
the fileUserId.txt should look like this:
1||2||
But he overwrites the file so it becomes this:
2||
What i am doing wrong?
Remove the fopen and fclose line and you are fine. file_put_contents does this internally. And fopen("fileUserId.txt", "w") clears the file.
Note:
'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.
You can as well do it differently. The commented code below illustrates how:
<?php
$txtFile = __DIR__ . "/fileUserId.txt";
$UserID = 9; //<== THIS VALUE IS FOR TESTING PURPOSES,
//<== YOU SHOULD HAVE ACCESS TO THE ORIGINAL $UserID;
//CHECK THAT THE FILE EXISTS AT ALL
if( file_exists($txtFile) ){
// GET THE CONTENTS OF THE FILE... & STORE IT AS A STRING IN A VARIABLE
$fileData = file_get_contents($txtFile);
// SPLIT THE ENTRIES BY THE DELIMITER (||)
$arrEntries = preg_split("#\|\|#", $fileData);
// ADD THE CURRENT $UserID TO THE $arrEntries ARRAY
$arrEntries[] = $UserID;
// RE-CONVERT THE ARRAY TO A STRING...
$strData = implode("||", $arrEntries);
// SAVE THE TEXT FILE BACK AGAIN...
file_put_contents($txtFile, $strData);
}else{
// IF FILE DOES NOT EXIST ALREADY, SIMPLY CREATE IT
// AND ADD THE CURRENT $UserID AS THE FIRST ENTRY...
file_put_contents($txtFile, $UserID);
}
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 ?
$file = fopen("contacts.csv","w");
foreach(array_unique($matches[0]) as $email) {
fputcsv($file,explode(',',$email));
}
fclose($file);
The above code generates a CSV file. How can I update the CSV from the last recorded line without overwriting from the beginning?
Change "w" to "a" in the fopen. It changes "write" into "append".
"append" opens the file and writes at the end of the file, not from the beginning like "write".
i.e. change this line
$file = fopen("contacts.csv","w");
to
$file = fopen("contacts.csv","a");
I have read a lot of questions, none of which worked. I have a txt file. The first line contains headers separated by a tab "\n". Now when i post to this file I want it to take the values and separate them by a tab and then write them on a new line of the txt file. But when I run it, it just overwrites the first line.
<?php
$post = $_POST;
$myFile = 'test.txt';
$fh = fopen($myFile, 'w');
$columns = "";
foreach ($post as $key => $value){
$columns .= $value . "\t";
}
fwrite($fh, $columns . PHP_EOL);
fclose($fh);
?>
You're looking for a instead w:
$fh = fopen($myFile, 'a');
From the docs:
'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.
w is used for writing which means anything before gets overwritten.
Change the following line:
$fh = fopen($myFile, 'w'); //w = write
To
$fh = fopen($myFile, 'a'); //a = append
It should fix the issue for you.
Try $fh = fopen($myFile, 'a'); if you don't want to overwrite content.
Using w overwrites, while a or a+ appends.
For more information on the fwrite() function, you can consult the PHP manual.
http://php.net/manual/en/function.fwrite.php
Also consult the PHP manual on fopen() http://php.net/manual/en/function.fopen.php
'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.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.