When I request this URL:
http://example.com/csv_build.php?filename=test.txt&time=1485902100000&data=25
I expect the PHP code to create a file named : datafile.txt that will contain the following data:
test.txt,1485902100000,25<CR><LF>
For some reason, datafile.txt is not created.
Did I made a mistake ?
<?
# GRAB THE VARIABLES FROM THE URL
$File = 'datafile.txt';
$FileName = $_GET['filename'];
$HeureTronconMesure = $_GET['time'];
$DonneeCapteur = $_GET['data'];
# --------------------------------
$FICHIER = fopen($File, "a");
#ftruncate($FICHIER,0);
fputs($FICHIER, $FileName);
fputs($FICHIER , ",");
fputs($FICHIER, $HeureTronconMesure);
fputs($FICHIER , ",");
fputs($FICHIER, $DonneeCapteur);
fputs ($FICHIER , "\r\n");
fclose($FICHIER);
?>
You're not doing any error checking. Why do you assume everything will work okay? If you spot some errors, first thing I would check is file permissions.
<?php
# GRAB THE VARIABLES FROM THE URL
$File = str_replace("/", "_", $_GET["filename"]);
$FileName = $_GET['filename'];
$HeureTronconMesure = $_GET['time'];
$DonneeCapteur = $_GET['data'];
# --------------------------------
if (!$FICHIER = fopen($File, "a")) {
//there was an error opening the file, do something here
}
fputs($FICHIER, $FileName);
fputs($FICHIER , ",");
fputs($FICHIER, $HeureTronconMesure);
fputs($FICHIER , ",");
fputs($FICHIER, $DonneeCapteur);
fputs ($FICHIER , "\r\n");
fclose($FICHIER);
?>
Though really, I'd simplify this code immensely by using some shortcuts and concatenating strings.
<?php
// replace any slashes in the filename with underscores
$file = str_replace(["/", "\\"], "_", $_GET["filename"]);
// build a string out of your data
$data = "$_GET[filename],$_GET[time],$_GET[data]\r\n";
// write the data to the file, checking if it returns false
if (!file_put_contents($file, $data)) {
//there was an error writing the file, do something here
}
Note, never open your code with <?, it's been deprecated a very long time now. Use <?php.
Related
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
i was wondering if it is posible to delete a single line in a txt file with php.
I am storing emailadresses in a flat txt file named databse-email.txt
I use this code for it:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email-subscribe'] . ',' . "\n";
$store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
if($store === false) {
die('There was an error writing to this file');
}
else {
echo "$email successfully added!";
}
}
?>
Form:
<form action="" method="POST">
<input name="email-subscribe" type="text" />
<input type="submit" name="submit" value="Subscribe">
</form>
The content of the file looks like this:
janny#live.nl,
francis#live.nl,
harry#hotmail.com,
olga#live.nl,
annelore#mail.ru,
igor#gmx.de,
natasha#hotmail.com,
janny.verlinden#gmail.com,
All lines are , seperated
Lets say i want to delete only the emailadres: igor#gmx.de
How can i do that?
What i want to achieve is a unsubscribe form and delete a single line in the .txt file
You can use str_replace
$content = file_get_contents('database-email.txt');
$content = str_replace('igor#gmx.de,', '', $content);
file_put_contents('database-email.txt', $content);
Because of the way the filesystem works you can't do this in an intuitive way. You have to overwrite the file with all the lines except the one you want to delete, here's an example:
$emailToRemove = "igor#gmx.de";
$contents = file('database-email.txt'); //Read all lines
$contents = array_filter($contents, function ($email) use ($emailToRemove) {
return trim($email, " \n\r,") != $emailToRemove;
}); // Filter out the matching email
file_put_contents('database-email.txt', implode("\n", $contents)); // Write back
Here's a streaming alternative solution in the cases where the file does not fit in memory:
$emailToRemove = "igor#gmx.de";
$fh = fopen('database-email.txt', "r"); //Current file
$fout = fopen('database-email.txt.new', "w"); //New temporary file
while (($line = fgets($fh)) !== null) {
if (trim($line," \n\r,") != $emailToRemove) {
fwrite($fout, $line, strlen($line)); //Write to new file if needed
}
}
fclose($fh);
fclose($fout);
unlink('database-email.txt'); //Delete old file
rename('database-email.txt.new', 'database-email.txt'); //New file is old file
There is also a way to do this in-place to minimize extra disk needed but that is trickier.
You can do it programmatically which will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file . Like below
$DELETE = "igor#gmx.de";
$data = file("database-email.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("database-email.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
first read the file using fopen and fget , and make array to list the emails you want to remove , use in_array to check if value exists in array , and then after remove unwanted emails save the file using fwrite and you need to close the file after the read and the write operations using fclose
checkout this code
$data = "";
$emailsToRemove = ["igor#gmx.de" , "janny#live.nl"];
//open to read
$f = fopen('databse-email.txt','r');
while ($line = fgets($f)) {
$emailWithComma = $line . ",";
//check if email marked to remove
if(in_array($emailWithComma , $emailsToRemove))
continue;
$data = $data . $line;
}
fclose($f);
//open to write
$f = fopen('databse-email.txt','w');
fwrite($f, $data);
fclose($fh);
for delete special word and next delete blank line try this:
$file = "file_name.txt";
$search_for = "example_for_remove";
$file_data = file_get_contents($file);
$pattern = "/$search_for/mi";
$file_data_after_remove_word = preg_replace($pattern, '', $file_data);
$file_data_after_remove_blank_line = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $file_data_after_remove_word);
file_put_contents($file,$file_data_after_remove_blank_line);
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 this script :
<?php
date_default_timezone_set('Europe/Berlin');
$date = date('d/m/Y h:i', time());
$ip = getenv("REMOTE_ADDR");
echo read_and_delete_first_line('data.txt');
function read_and_delete_first_line($filename) {
$file = file($filename);
$output = $file[0];
unset($file[0]);
file_put_contents($filename, $file);
$file1 = fopen($filename, "a");
fputs ($file1, $output);
fclose ($file1);
return $output;
}
?>
this get the first line of file and move to last file, the problem is, if receve more request in same time, php remove all data from data.txt and save file empty .. how can resolve this problem ? is possible whit this method or need use mysql ?
So I have a JSON file containing basketball player information in the following format:
[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]
I want a user to be a able to add their own custom players to this file. To do this i try the following:
<?php
$json = file_get_contents('json/players.json');
$info = json_decode($json, true);
$info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
file_put_contents('json/players.json', json_encode($info));
?>
This "sort of" works. But when I check the JSON file, I find that there are 3 new entries rather than 1:
{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}
assuming $name="Jeff" $team=3 and $ppg=23 (populated via POST submission).
What's going on and how can I fix it?
You could try doing the following:
Untested code
<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
$fh = fopen('json/players.json', 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);//removes last ] char
fclose($fh);
$fh = fopen('json/players.json', 'a');
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
fwrite($fh, ','.json_encode($info).']');
fclose($fh);
}
?>
This will append the only the new json to the file instead of opening the file, making php parse all the json and then writing it to the file again. In addition to that it will only store the data if the variables actually contain data.
Try this:
<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];
//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
//Open the file
$fh = fopen('json/players.json', 'r+') or die("can't open file");
//get file info/stats
$stat = fstat($fh);
//final desired size after trimming the trailing ']'
$size = $stat['size']-1;
//file has contents? then remove the trailing ']'
if($size>0) ftruncate($fh, $size);
//close the current handle
fclose($fh);
// reopen the file for append
$fh = fopen('json/players.json', 'a');
//build your data array
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
//if this is not the first item on file
if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
else fwrite($fh, '['.json_encode($info).']'); //first item on file
fclose($fh);
}
?>
Maybe your php config is not set to convert the post/get variables to global variables. This happened to me a couple of times so I rather create the variables I'm expecting from the post/get request. Also watch out for the page encoding, from personal experience you could be getting empty strings there.
I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/