I have php code that open an txt file then click click enter 2 times, then write data
sample
1
2
3
i just want help to write same data but in first line in txt file
mean php open the txt then go to first line and before the texts, and click enter two times then enter the same data, sample will be
3
2
1
this is my code
<?php
if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$nice=$_POST['namee'];
$date = date('m/d/Y h:i:s a', time());
date_default_timezone_set('Etc/GMT-3');
$fp = fopen('data.txt', 'a');
~ here I want code to select first line in txt file
fwrite($fp, "\n" );
fwrite($fp, "\n" );
fwrite($fp,date('Y-m-d') . ' - ' . date('H:i:s'). "\n");
fwrite($fp, $nice);
As mentioned in the comments, opening the file with fopen('data.txt', 'r+') will set the file pointer to the beginning of the file.
Also, once you have already written something, it's possible to set the file pointer to a new location (e.g. beginning of the file):
fseek($fp, 0) - this sets the file pointer to the beginning of the file.
You can also use: rewind($fp), which does the same thing.
If I understand correctly, you want to prepend something to the file... does it have to be with fopen()?
In my opinion easier and much more understandable solution, but uses more memory, as it loads the whole file, so not usable on huge files:
<?php
$toPrepend = "\n\n";
$myFile = 'data.txt';
file_put_contents($myFile, $toPrepend . file_get_contents($myFile));
You can also load whole file into an array (every item of array will be one line) with:
<?php
$file_lines = file($myFile);
And then change any line you want, like
<?php
$file_lines[0] = 'add this before the first line' . $file_lines[0];
$file_lines[1] = 'add this before the second line' . $file_lines[1];
$file_lines[2] = trim($file_lines[2]) . 'add this after the third line' . "\n"
// last one is more complicated, as every line ends with EOL character(s);
And save it:
<?php
file_put_contents($myFile,implode("",$file)); // you need to implode array to string
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
What is the best way for adding a line to a textfile? When I run the below code, it overwrites all lines.
Also when adding a line it contains some "s:4:" & s:60: characters. What does this mean? I just want to add the $photourl to urls.txt.
<?php
foreach ($_POST['photoselect'] as $photourl) {
file_put_contents($target_dir . '/urls.txt', $photourl);
$fp = fopen($target_dir . '/urls.txt','w');
fwrite($fp,serialize($photourl));
}
?>
You can append with file_put_contents
file_put_contents($target_dir . '/urls.txt', $photourl, FILE_APPEND);
When opening a file, the last parameter indicates how you want the file pointer to be set. With 'w', this truncates the file, you probably want to have 'a' which means put the pointer at the end of the file. ( see http://php.net/manual/en/function.fopen.php modes )
Unless you content contains special characters, just write it and not serialize it.
Your code also overwrites the file each time...
$fp = fopen($target_dir . '/urls.txt','a');
foreach ($_POST['photoselect'] as $photourl) {
fwrite($fp,$photourl.PHP_EOL);
}
fclose($fp);
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 ?
I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);
Is it possible to put the file_put_contents() function inside a while() loop?
I am trying to get my script to write lines into a text file - there's over 4 thousand lines to write.
$glassquery = $db->query("SELECT item FROM glass");
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL);
}
So it's writing the item name into the text file then the next one on a new line.
I think what you want is the FILE_APPEND flag:
while($glass = $glassquery->fetch_assoc()) {
file_put_contents('download.txt', $glass['item'] . PHP_EOL, FILE_APPEND);
}
This will write the lines one at a time without erasing previous lines.