Here is the script normally. It saves data to a file.
<?php
if (isset($_GET['field'])) {
$file = 'data.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n".$_GET['field'];
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
But I want it to add (added by a user) at the end of what is sent. I have tried this:
<?php
if (isset($_GET['field'])) {
$file = 'data.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n".$_GET['field'] + "(added by a user)";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
But it doesn't work. How do I do this?
Related
How Write on a file in the last line without clean the all content of the document:
if($query>9999){
$file = file_get_contents(' /home/server/public_html/.htaccess');
$checklist = ".htacess";
#deny from 210.126.173.80
$sheriff = 'deny from '.$ip;
#Check if a text file exists. If not create one and initialize it to zero.
#$f = fopen($counter_name, "w");
$f = fopen($checklist, $sheriff);
fwrite($f,$file);
fclose($f);
}
i tried to search, but still dont know the solution at all, for my next PHP code.
<?php
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = '/home/cs2d/sys/lua/weather.dat';
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
As you can see it's a simple code, which write values into the weather.dat file.
But how to possible to do that its just refresh lines instead of add new one.
Any idea?
This works :
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = 'weather.dat';
$current = file_get_contents($file);
$contents = file_get_contents($file);
echo $current;
$contents = str_replace($current, ' ', $contents);
echo $contents;
file_put_contents($file,$contents);
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
So, I have a code that based on user's input write data to the file. Basically user select the date and the workout which on submit get written to the file. When I try to set it up to check if the string (date) already exist in the file I cannot make it work so that existing line is replaced.
Current code that is writing user's input to the file:
<?php
include 'index.php';
$pickdate = $_POST['date'];
$workout = $_POST['workout'];
$date = ' \''.$pickdate .'\' : \'<span>'.basename($workout,'.txt').'</span>\',' .PHP_EOL;
$file = 'test.js';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new workout to the file
$current .= $date;
$current = preg_replace('/};/', "", $current);
$current = $current.'};';
// Write the contents back to the file
file_put_contents($file, $current);
header("location:index.php");
?>
My attempts were with if statement but again I couldn't manage to write the code that will replace the line with if exists. This is what I have:
<?php
include 'index.php';
$pickdate = $_POST['date'];
$workout = $_POST['workout'];
$date = ' \''.$pickdate .'\' : \'<span>'.basename($workout,'.txt').'</span>\',' .PHP_EOL;
$file = 'test.js';
// Open the file to get existing content
$current = file_get_contents($file);
if (strpos($current, ' \''.$pickdate .'\'') ) {
#here is where I struggle#
}
else {
// Append a new workout to the file
$current .= $date;
$current = preg_replace('/};/', "", $current);
$current = $current.'};';
// Write the contents back to the file
file_put_contents($file, $current);
}
header("location:index.php");
?>
Currently it is doing this
08-04-2014 : Chest
08-05-2014 : Legs
08-04-2014 : Back
I want this
Now when user choose August 4th again that line to be replaced with new/same choice of workout depending what user selects.
08-04-2014 : Back
08-05-2014 : Legs
Can someone help with the part where I struggle to make this work. Thank you so much in advance.
As explained by Barmar in the comments:
$current = trim(file_get_contents($file));
$current_lines = explode(PHP_EOL, $current);
/* saved already */
$saved = false;
foreach($current_lines as $line_num => $line) {
/* either regex or explode, we explode easier on the brain xD */
list($date_line, $workout_line) = explode(' : ', $line);
echo "$date_line -> $workout_line \n";
if($date == $date_line) {
/* rewrite */
$current_lines[$line_num] = "$date : $workout";
$saved = true;
/* end loop */
break;
}
}
/* append to the end */
if(!$saved) {
$current_lines[] = "$date : $workout";
}
file_put_contents($file, implode(PHP_EOL, $current_lines));
So, you explode the file, go thru it, line by line, if found overwrite that line, if not append it to the end of the array, then glue it back together and put it back in the file.
You'll get the idea.
Hope it helps.
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
}
?>
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));
}