How to replace line in the file if exists PHP - php

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.

Related

How do I add text at the end of this PHP script

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?

Whether PHP writes file

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);

File manupulation search and replace csv php

I need a script that is finding and then replacing a sertain line in a CSV like file.
The file looks like this:
18:110327,98414,127500,114185,121701,89379,89385,89382,92223,89388,89366,89362,89372,89369
21:82297,79292,89359,89382,83486,99100
98:110327,98414,127500,114185,121701
24:82297,79292,89359,89382,83486,99100
Now i need to change the line 21.
This is wat i got so far.
The first 2 to 4 digits folowed by : ar a catergory number. Every number after this(followed by a ,) is a id of a page.
I acces te id's i want (i.e. 82297 and so on) from database.
//test 2
$sQry = "SELECT * FROM artikelen WHERE adviesprijs <>''";
$rQuery = mysql_query ($sQry);
if ( $rQuery === false )
{
echo mysql_error ();
exit ;
}
$aResult = array ();
while ( $r = mysql_fetch_assoc ($rQuery) )
{
$aResult[] = $r['artikelid'];
}
$replace_val_dirty = join(",",$aResult);
$replace_val= "21:".$replace_val_dirty;
// file location
$file='../../data/articles/index.lst';
// read the file index.lst
$file1 = file_get_contents($file);
//strip eerde artikel id van index.lst
$file3='../../data/articles/index_grp21.lst';
$file3_contents = file_get_contents($file3);
$file2 = str_replace($file3_contents, $replace_val, $file1);
if (file_exists($file)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
if (file_exists($file3)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
// replace the data
$file_val = $file2;
// write the file
file_put_contents($file, $file_val);
//write index_grp98.lst
file_put_contents($file3, $replace_val);
mail('info#', 'Aanbieding catergorie geupdate', 'Aanbieding catergorie geupdate');
Can anyone point me in the right direction to do this?
Any help would be appreciated.
You need to open the original file and go through each line. When you find the line to be changed, change that line.
As you can not edit the file while you do that, you write a temporary file while doing this, so you copy over line-by-line and in case the line needs a change, you change that line.
When you're done with the whole file, you copy over the temporary file to the original file.
Example Code:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
This part is just setting up the basics: The category, the IDs of the articles and then building the related strings.
Now opening the file to change the line in:
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
The file is locked so that no other process can edit the file while it gets changed. Next to that file, the temporary file is needed, too:
$temp = new SplTempFileObject(4096);
After setting up the two files, let's go over each line in $file and compare if it needs to be replaced:
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
Now the $temporary file contains already the changed line. Take note that I used UNIX type of EOF (End Of Line) character (\n), depending on your concrete file-type this may vary.
So now, the temporary file needs to be copied over to the original file. Let's rewind the file, truncate it and then write all lines again:
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
And finally you need to lift the lock:
$file->flock(LOCK_UN);
And that's it, in $file, the line has been replaced.
Example at once:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
$temp = new SplTempFileObject(4096);
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
$file->flock(LOCK_UN);
Should work with PHP 5.2 and above, I use PHP 5.4 array syntax, you can replace [111182297, ...] with array(111182297, ...) in case you're using PHP 5.2 / 5.3.

Simple Site Stat script not gathering data from file, I have an almost exact script that works

I made a script a while ago that wrote to a file, I did the same thing here, only added a part to read the file and write it again. What I am trying to achive is quite simple, but the problem is eluding me, I am trying to make my script write to a file basically holding the following information
views:{viewcount}
date-last-visited:{MM/DD/YYYY}
last-ip:{IP-Adress}
Now I have done a bit of research, and tried several methods to reading the data, none have returned anything. My current code is as follows.
<?php
$filemade = 0;
if(!file_exists("stats")){
if(!mkdir("stats")){
exit();
}
$filemade = 1;
}
echo $filemade;
$hwrite = fopen("stats/statistics.txt", 'w');
$icount = 0;
if(filemade == 0){
$data0 = file_get_contents("stats/statistics.txt");
$data2 = explode("\n", $data0);
$data1 = $data_1[0];
$ccount = explode(":", data1);
$icount = $ccount[1] + 1;
echo "<br>icount:".$icount."<br>";
echo "data1:".$data1."<br>";
echo "ccount:".$ccount."<br>";
echo "ccount[0]:".$ccount1[0]."<br>";
echo "ccount[1]:".$ccount1[1]."<br>";
}
$date = getdate();
$ip=#$REMOTE_ADDR;
fwrite($hwrite, "views:" . $icount . "\nlast-viewed:" . $date[5] . "/" . $date[3] . $date[2] . "/" . $date[6] . "\nlast-ip:" . $ip);
fclose($hwrite);
?>
the result is always:
views:1
last-viewed://
last-ip:
the views never go up, the date never works, and the IP address never shows.
I have looked at many sources before finally deciding to ask, I figured I'd get more relevant information this way.
Looking forward to some replies. PHP is my newest language, and so I don't know much.
What I have tried.
I have tried:
$handle_read = fopen("stats/statistics.txt", "r");//make a new file handle in read mode
$data = fgets($handle_read);//get first line
$data_array = explode(":", $data);//split first line by ":"
$current_count = $data_array[1];//get second item, the value
and
$handle_read = fopen("stats/statistics.txt", "r");//make a new file handle in read mode
$pre_data = fread($handle_read, filesize($handle_read));//read all the file data
$pre_data_array = explode("\n", $pre_data);//split the file by lines
$data = pre_data_array[0];//get first line
$data_array = explode(":", $data);//split first line by ":"
$current_count = $data_array[1];//get second item, the value
I have also tried split instead of explode, but I was told split is deprecated and explode is up-to-date.
Any help would be great, thank you for your time.
Try the following:
<?php
if(!file_exists("stats")){
if(!mkdir("stats")) die("Could not create folder");
}
// file() returns an array of file contents or false
$data = file("stats/statistics.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!$data){
if(!touch("stats/statistics.txt")) die("Could not create file");
// Default Values
$data = array("views:0", "date-last-visited:01/01/2000", "last-ip:0.0.0.0");
}
// Update the data
foreach($data as $key => $val){
// Limit explode to 2 chunks because we could have
// IPv6 Addrs (e.x ::1)
$line = explode(':', $val, 2);
switch($key){
case 0:
$line[1]++;
break;
case 1:
$line[1] = date('m/d/Y');
break;
case 2:
$line[1] = $_SERVER['REMOTE_ADDR'];
break;
}
$data[$key] = implode(':', $line);
echo $data[$key]. "<br />";
}
// Write the data back into the file
if(!file_put_contents("stats/statistics.txt", implode(PHP_EOL, $data))) die("Could not write file");
?>

Search a file and migrate search term is in to a new file

This code enables to create a new .txt file, if the file doesn't exist yet, it will create the file.
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
And this code here identifies each line of string into a token.
<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well */
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
?>
The people.txt looks like this
John Smith
John Meyer
John Chase
John Smith //i want to transfer this set of string into a new file
What am i missing here?
$searchTerm = 'John Smith';
$file = 'people.txt';
$fileFound = 'peopleFound.txt';
$current = file_get_contents($file);
if (strpos($searchTerm, $current) !== false) {
file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND);
}
$fp=fopen('people.txt','a+');
fputs($fp,"John Smith\r\n");
fclose($fp);
open and append the file, don't read it all in and append to the back and write it all back out. when the file gets past a certain size that will be real inefficient. I'm not sure how it is you're trying to tokenize it. seems to me you could just do a $names=file('people.txt'); and have them in an array immediately...

Categories