PDA

View Full Version : Save form data in a txt file with current date in file name



trazix
06-07-2009, 11:17 PM
I use the following script to save the data from a form to a txt file on the server with the name file_name.txt. What i would like is for the file name to be the date and time the file was posted in UTC eg. 2009-06-09-13-45-59.txt (year-month-day-hour-minute-second.txt)



<?php


// retrieve form data
$input = $_POST['msg'];



// Open the file and erase the contents if any

$fp = fopen("file_name.txt", "r+");



// Write the data to the file

fwrite($fp, $input).'&nbsp;';



// Close the file

fclose($fp);



?>

bluewalrus
06-08-2009, 12:28 AM
Do you only want 1 text file?

traq
06-08-2009, 02:52 AM
you want a new file every time someone submits the form, correct? try this:


<?php
$input = $_POST['msg'];
$dateposted = date("YmdHis");
$fp = fopen("$dateposted.txt", "w");
fwrite($fp, $input).'&nbsp;';
fclose($fp);
?>

Notes:
1) Tested and works.
2) You would be well-advised to validate or sanitize the user input before writing it to a file, especially if you plan on using the contents later.
3) You need to change the write mode to "w" instead of "r+".
4) This names the file using 24-hr time (e.g., "20090607195136.txt"). if you want 12-hr time (e.g., "20090607075136.txt"), use this:


$dateposted = date("Ymdhis");

though this could result in duplicate file names (thereby overwriting earlier submissions), IF someone happened to submit their form EXACTLY 12 hours after someone else did, unless you add AM or PM to the name (e.g., "20090607075136pm.txt"):


$dateposted = date("Ymdhisa");


If you want the dashes, use: $dateposted = date("Y-m-d-H-i-s"); -I think I prefer it without, but it's your file. :)

Read up here (http://www.tizag.com/phpT/phpdate.php).

trazix
06-08-2009, 05:26 PM
Excellent work traq

One thing "YmdHis" this does not write the time in 24hour format e.g. 6pm comes out as 0600 and not 1800 as it should be. Could this be a server issue as i see the time that the file is uploaded as 06:00.

Also you mentioned validation and sanitzation it sounds very complicated, how could you scan the file for bad words and replace them with blanked out words.

traq
06-08-2009, 11:56 PM
One thing "YmdHis" this does not write the time in 24hour format... Could this be a server issue as i see the time that the file is uploaded as 06:00.
odd. It did when I tested it on my server. That's what it's supposed to do.
It could be a server issue. If you server is in a different time zone than you are (which is fairly likely), it could be 6AM there and not PM. Other than that, I don't know.


Also you mentioned validation and sanitzation it sounds very complicated, how could you scan the file for bad words and replace them with blanked out words.

By validation/ sanitization I didn't mean checking for bad words, etc., but checking that no harmful code is inadvertently saved to your website. For a start, read about htmlentities() (http://www.tizag.com/phpT/php-htmlentities.php).

You can find plenty of scripts that will search out and censor bad words, too. Just do a Google search.

trazix
06-14-2009, 06:38 PM
I checked the location of the server and it is in Malysia, which is +8 hours from my time zone GMT.

What if I wanted to use a number as the file name instead which increments by one every time a file is saved. What modification to the code would be needed.

traq
06-15-2009, 02:11 AM
you could use a database or a text file to keep track of the last file name. A text file would be simpler. try this:


<?php
if (isset($_POST['msg'])){
//process message if submitted
if (file_exists("filecount.txt")){
//find out if there is a file count file
$filename = file_get_contents("filecount.txt");
//if so, use the stored number as the filename
} else {
//if not,
$filename = 1;
//set the filename to "1"
$fCount = fopen("filecount.txt", "w");
//then create the file count file
fwrite($fCount, "2");
//set its contents to "2", which will be the next filename
fclose($fCount);
//and close it
}
$input = $_POST['msg'];
if (!file_exists("$filename.txt")){
//if the filename is not already in use,
$fp = fopen("$filename.txt", "w");
fwrite($fp, $input).'&nbsp;';
fclose($fp);
//write the submitted message to a file using the file name
$fInc = fopen("filecount.txt", "w");
//then, open the file count file
fwrite($fInc, (++$filename));
//add one to the value and rewrite it (now it's ready for the next submission)
fclose($fInc);
//and close it
} else {
echo "Couldn't save your message: File name already exists!";
//otherwise, send an error message and DON'T OVERWRITE THE FILE!
//some code could be developed here to choose a suitable filename, but I'm not sure how it would go
}
}
?>

The first else{} block (the one that writes the initial "filecount.txt" file) is only intended to be used the first time a message is submitted. It could be left out if you prefer to create that file manually and upload it to the same directory.

There's probably a way to read through the filenames and find the next one in line, but I'm not sure how to do it. But at that point, you wouldn't need the "filecount.txt" file in the first place.

trazix
06-16-2009, 10:46 PM
Excellent work traq, you must know this php insideout, I am very much a novice at it. The file number is probably a better method.

Now how could i get the content from these files and write them to a web page starting with the highest file number and placing it inside a table or Div for example.

traq
06-17-2009, 02:04 AM
I'm glad I could help, but you are overestimating my ability. I've only been using php for a few months, and I'm still learning most of it. I try to make good use of tutorials, and I spend lots of time googling various error messages. If you're good with logic and troubleshooting, learning the basics of php shouldn't be too hard. That last bit (incrementing file naming) took me quite a bit of trial-and-error, and most of it is adapted from several php hit counter tutorials. Just try stuff and change one bit at a time until it all works.

I have an idea of what would need to be done for what you're asking, but ATM I can only figure how to do it forwards. You need to find a function that will get all the filenames from a directory and loop through them in descending order... Give me a while and we'll see what we can figure out.

traq
06-17-2009, 06:20 PM
Okay: here's what I have so far:


<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Comments:
<textarea name="msg">I am layzeeee don't wanna type for each test</textarea>
<input type="submit" value="submit">
</form>
<?php
if (isset($_POST['msg'])){
//process message if submitted
if (file_exists("filecount.txt")){
//find out if there is a file count file
$filename = file_get_contents("filecount.txt");
//if so, use the stored number as the filename
} else {
//if not,
$filename = 1;
//set the filename to "1"
$fCount = fopen("filecount.txt", "w");
//then create the file count file
fwrite($fCount, "2");
//set its contents to "2", which will be the next filename
fclose($fCount);
//and close it
}
$input = $_POST['msg'];
if (!file_exists("write/$filename.txt")){
//if the filename is not already in use,
$fp = fopen("write/$filename.txt", "w");
fwrite($fp, $input).'&nbsp;';
fclose($fp);
//write the submitted message to a file using the file name
$fInc = fopen("filecount.txt", "w");
//then, open the file count file
fwrite($fInc, (++$filename));
//add one to the value and rewrite it (now it's ready for the next submission)
fclose($fInc);
//and close it
}

function directory($result) {
$h=opendir("write");
while ($file = readdir($h)) {
if ($file == "." || $file == "..") {
//do nothing
} else {
$RAWfilecontent = file_get_contents("write/$file");
$filecontent = filter_var($RAWfilecontent, FILTER_SANITIZE_STRING);
print '
<div id="'.$file.'" class="entry">
'.$filecontent.'
</div>';
}
}
closedir($h);
return $result;
}
echo '<b>Comments submitted so far:</b>';
echo directory($result);
}
?>

This creates a filecount file, as before, and writes each submitted comment. This time, it saves those text files in another directory (write). This directory must contain only the comment submissions (1.txt, 2.txt, etc.).

The function at the end reads the "write" directory and prints the contents of each comment file inside a <div> at the bottom of the page. FILTER_SANITZIE_STRING strips any code tags from the file contents to help prevent an attacker from running code through their comments.

It works, however, there is no check on each file's type. The script assumes that all the files in the directory are supposed to be used. If a non-text file gets into the directory somehow, you could end up running code you didn't intend to.

I've tried using various functions, including finfo() and mime_content_type, to verify the file type as plain text, but I can't get them to work properly yet.

Working example here (http://www.custom-anything.com/sand/test.php).

trazix
06-20-2009, 08:26 PM
I cant get this to work, I put the code inside html, head and body tags and saved it as .php file it just displays a page of the code and nothing else.

How did you test it. Am I doing something wrong

traq
06-21-2009, 12:16 AM
damn spam...
no more spam! thanks

I cant get this to work, I put the code inside html, head and body tags and saved it as .php file it just displays a page of the code and nothing else.

How did you test it. Am I doing something wrong

The actual php code displays? Check your <?php ?> tags and make sure you have all the php code contained within. You also need to create a subdirectory named "write" in the same directory as this file. Otherwise, I'm not sure what the problem would be. The code I posted is *exactly* what I have online here (http://www.custom-anything.com/sand/test.php).

trazix
06-21-2009, 01:27 PM
Got the web page to display but when i click Submit I get this message

Comments submitted so far:
Fatal error: Call to undefined function filter_var() in /www/htdocs/TEST.php on line 50

Not sure what could be wrong your code is just copy and pasted to my file.

thetestingsite
06-21-2009, 03:53 PM
What version of PHP do you have installed? If it is below PHP 5, then filter_var (http://www.php.net/filter_var) will not work.

Hope this helps.

traq
06-21-2009, 04:15 PM
yeah. contact your webhost; sometimes they can upgrade. 1and1, for example, advertises php5 but runs php4 by default and you have to use .htaccess to switch to php5.

alternatively, replace this line:

$filecontent = filter_var($RAWfilecontent, FILTER_SANITIZE_STRING);
with this:

$filecontent = htmlentities($RAWfilecontent);
which will also make the user input safer, but won't look as nice. For example, if someone tried to attack your site by saving a message like this:


<script type="text/javascript">
window.location = "www.endlesspopups.com"
</script>

FILTER_SANITIZE_STRING would strip the tags (preventing the code from running) and display it like this:

window.location = "www.endlesspopups.com"
and htmlentities would encode the < > characters (preventing the code from running) and display the original message just as you see it above.

trazix
06-21-2009, 05:06 PM
It'S PHP Version 5.1.6 , I am using a freehost service just for testing and learning.

I modified that line and it works, but the posted messages are not in the order they were posted it semes to be random.

traq
06-21-2009, 10:52 PM
If you're running php5, then filter_var ought to work (and would be preferable, IMO). Likewise, I don't know why the messages would be being displayed in random order. Would you link to your test page?

trazix
06-25-2009, 07:27 PM
Link to test page
http://yabadabadoo.blackapplehost.com/_AAA/New%20TEST.php

Link to Php info page
http://yabadabadoo.blackapplehost.com/_AAA/PHP%20Server%20Info.php

traq
06-26-2009, 01:27 AM
... no idea.
it does seem to be random. but it seems to always be in the same random order (except for each new submission, of course).

trazix
06-27-2009, 07:28 PM
I have come up with a solution to show the files from the last one posted, first i open the filecount.txt file and get the number stored in it, then i use it to count backwards and then include the .txt file on the page. Here is the code


<?php
$filename= "filecount.txt" ;
$fd = fopen ($filename , "r") or die ("Can't open $filename") ;
$fstring = fread ($fd , filesize ($filename)) ;

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

include('write/'.--$fstring.'.txt');

fclose($fd) ;

?>
And a link to it
http://yabadabadoo.blackapplehost.com/_AAA/Showfiles.php

Now the problem here i all the text is bunched together.
What i would like is to have a break between each file include, I tryed putting in echo <br> but nothing would display.

Also the code is long I am sure a loop or something could be writen to do what all the above includes are doing, If posible i would like it to just display the last 20 files posted with a link then for the next 20 and so on, I hope somebody is up to this challenge a my php is very basic and getting the above code working was not easy for me.

trazix
06-27-2009, 08:15 PM
I've cracked the loop by myself here the code

<?php
$filename= "filecount.txt" ;
$fd = fopen ($filename , "r") or die ("Can't open $filename") ;
$fstring = fread ($fd , filesize ($filename)) ;

for ($i = $fstring; ; $i--) {
if ($i <= 0) {
break;
}
include('write/'.$i.'.txt');
}

fclose($fd) ;

?>
And Link
http://yabadabadoo.blackapplehost.com/_AAA/Show_all_files.php

Still no space or break between Post's also the loop gets all files and is not limited to 20 files.

trazix
06-27-2009, 08:43 PM
I've now managed to seperate the files with a space and border, however there is a strange line at the top and down a few posts.

[edit] the strange lines are empty divs where a file is missing except the first one dont know what is causing it.

[Another edit]Ok deleted all files and reposted 30 times, now first file 0.txt is missing and at top of page an empty div is created.

Link
http://yabadabadoo.blackapplehost.com/_AAA/Show_all_files2.php


<?php
$filename= "filecount.txt" ;
$fd = fopen ($filename , "r") or die ("Can't open $filename") ;
$fstring = fread ($fd , filesize ($filename)) ;

for ($i = $fstring; ; $i--) {
if ($i <= 0) {
break;
}
echo "<div style='border: 1px #6D7B8D solid;'>";
include('write/'.$i.'.txt');
echo "</div><br>";
}

fclose($fd) ;

?>

trazix
06-28-2009, 11:43 AM
Ok here is where I am now, I've managed to get it to only display the last 10 post's by counting back 11 (why 11 and not 10 I dont know) probably something to do with that blank div at the top of page which i also managed to get rid of with this line $fstring_two = $fstring-1; . Not bad for an amature.

Anyway creating a link at bottom of page that will link to another 10 previous posts is proving hard to find a solution to, any ideas would be apreciated.

Link
http://yabadabadoo.blackapplehost.com/_AAA/Show_all_files3.php


<?php

$filename= "filecount.txt" ;
// Store file name to $filename

$fd = fopen ($filename , "r") or die ("Can't open $filename") ;
// Opens file and read's it's contents

$fstring = fread ($fd , filesize ($filename)) ;
// Stores file contents to $fstring

$fstring_two = $fstring-1;
//This stops a blank div displaying at top of page

$loop=$fstring-11;
//Set's a value of $fstring - 11 to $loop and only display's the last 10 entries


for ($i = $fstring_two; ; --$i) {
if ($i <= $loop) {
break;
} elseif ($i <= 0){
break;
}

echo "<div style='border: 1px #6D7B8D solid;'>";
// Writes Html

include('write/'.$i.'.txt');
// Includes txt files from write folder

echo "</div><br>";
// Writes Html

}

fclose($fd) ;
// Closes filecount.txt

?>

trazix
06-28-2009, 02:00 PM
I've integrated some of the older code with the newer code and have come up with this so far.
[Link]
http://yabadabadoo.blackapplehost.com/_AAA/TEST.php



<html>
<head>
</head>
<body>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<textarea name="msg"></textarea>
<input type="submit" value="submit">
</form>


<?php
if (isset($_POST['msg'])){
//process message if submitted
if (file_exists("filecount.txt")){
//find out if there is a file count file
$filename = file_get_contents("filecount.txt");
//if so, use the stored number as the filename
} else {
//if not,
$filename = 1;
//set the filename to "1"
$fCount = fopen("filecount.txt", "w");
//then create the file count file
fwrite($fCount, "2");
//set its contents to "2", which will be the next filename
fclose($fCount);
//and close it
}
$input = $_POST['msg'];
if (!file_exists("write/$filename.txt")){
//if the filename is not already in use,
$fp = fopen("write/$filename.txt", "w");
fwrite($fp, $input).'&nbsp;';
fclose($fp);
//write the submitted message to a file using the file name
$fInc = fopen("filecount.txt", "w");
//then, open the file count file
fwrite($fInc, (++$filename));
//add one to the value and rewrite it (now it's ready for the next submission)
fclose($fInc);
//and close it
}

function directory($result) {
/* This file shows the last 10 files posted to write directory */

$filename= "filecount.txt" ;
// Store file name to $filename

$fd = fopen ($filename , "r") or die ("Can't open $filename") ;
// Opens file and read's it's contents

$fstring = fread ($fd , filesize ($filename)) ;
// Stores file contents to $fstring

$fstring_two = $fstring-1;
//This stops a blank div displaying at top of page

$loop=$fstring-11;
//Set's a value of $fstring - 11 to $loop and only display's the last 10 entries


for ($i = $fstring_two; ; --$i) {
if ($i <= $loop) {
break;
} elseif ($i <= 0){
break;
}

echo "<div style='border: 1px #6D7B8D solid;'>";
// Writes Html

include('write/'.$i.'.txt');
// Includes txt files from write folder

echo "</div><br>";
// Writes Html

}

fclose($fd) ;
// Closes filecount.txt
}
echo '<b>Comments submitted so far:</b>';
echo directory($result);
}
?>
</body>

</html>