Grow your CSS skills. Land your dream job.

html form that will post to a .txt file

  • # May 1, 2012 at 10:45 am

    Can somebody please help me? I can’t figure how to make a html form post to a .txt file i know it takes a php script I just don’t know that much about php. All I need is first name, last name, and date. thanks.

    __
    # May 1, 2012 at 10:46 pm

    you can’t “post to a txt file.”
    well, you can, but it would be pointless.
    Post to a php script that will write to a txt file.

    What format do you want the form info to be saved in?
    Here’s an example using JSON:

    < ?php
    // check if a form was submitted
    if( !empty( $_POST ) ){
    // convert form data to json format
    $json = json_encode( $_POST );
    // make sure there were no problems
    if( json_last_error() != JSON_ERROR_NONE ){
    exit; // do your error handling here instead of exiting
    }
    // write to file
    // note: _server_ path, NOT "web address (url)"!
    file_put_contents( '/server/path/to/json.txt',$json );
    }

    This example will actually save any and all info your form submits.

    Depending on what you’re doing with the info, you might need to take extra precautions (for example, strip html tags if you need the file to be accessible via the web).

    # May 2, 2012 at 9:43 am

    I don’t know, i’ve never used json before. let me tell you what i’m doing. One of my customers sites has baby registries on it they want their employees to be able to change them without having to edit the html code manually. So I wanted to create a html input form that will post the name and date somewhere so another script would read the names and post them on a page. I already have the one that reads a .txt file but I may have to change it now.

    __
    # May 2, 2012 at 10:06 am

    Have you considered using a database? This is exactly the sort of thing they’re for.

    The. txt file approach will work also (and JSON is an excellent format for this purpose), but a DB is preferable.

    # May 2, 2012 at 10:33 am

    I’m sorry but I pretty new to development and I don’t know how to do that either.

    __
    # May 2, 2012 at 11:11 am

    ahh, but are you willing? (and it’s nothing to be sorry about!) Does your hosting plan include a database?

    If you’d rather use a .txt file, that’s fine too. Here’s a little more of an example based on your description:

    < ?php
    // check that form was submitted
    // (you'll need to change these indices to match your form field names)
    if( !empty( $_POST ) && !empty( $_POST ) ){
    // remove html tags from submission
    // (since you don't want them)
    $firstname = strip_tags( $_POST );
    $lastname = strip_tags( $_POST );
    // create the date
    // (you can change the format as desired)
    $date = date( 'Y-m-d' );
    // create an array that holds your info
    $record = array( $firstname,$lastname,$date );
    // save the record to your .txt file (I still recommend JSON)
    $json = json_encode( $record );
    $file = '/_server_/path/to/yourfile.txt';
    file_put_contents( $json,$file );
    }

    to retrieve the data later, you could use something like this:

    < ?php
    // read the .txt file into an array
    $file = '/_server_/path/to/yourfile.txt';
    $jsonarray = file( $file,FILE_IGNORE_NEW_LINES,FILE_SKIP_EMPTY_LINES );
    // convert each array element (each record) back into an array
    foreach( $jsonarray as $json ){
    $records[] = json_decode( $json,TRUE );
    }
    // loop through the records and write your html to display
    // (I'm guessing you're putting this data into a table)
    foreach( $records as $record ){
    // extract each variables
    list( $firstname,$lastname,$date ) = $record;
    // EDIT: added htmlentities() for safe output.
    $firstname = htmlentities( $firstname );
    $lastname = htmlentities( $lastname );
    // make an array of table rows
    $trs[] = "

    $firstname
    $lastname
    $date
    ";
    // cleanup
    unset( $firstname,$lastname,$date );
    }
    // prepare the table
    $table = '





    '.
    implode( '',$trs ).'
    First Name Last Name Date
    ';
    // when you're ready, print it to your page
    print $table;

    of course, this will vary depending on how you want to display the data, but that’s the basic idea.

    You could probably modify the way you store the data to match the way your current script reads the .txt file, but that might be more trouble than it’s worth …it would depend. The approach in my example is a good one, however.

    Using a database instead would:
    – be more robust
    – require less code to prepare/store/retrieve/decode the data
    – allow you to search for specific records efficiently if the need ever arose

    ?, lmk

    # May 2, 2012 at 11:56 am

    I’m willing but I’m in high school so I might not be able to do everything right away. Also I’m with media temple so I’m pretty sure I can make a database pretty easy if your willing to help me everything.

    __
    # May 2, 2012 at 1:16 pm

    When you have a chance, read up on some sql tutorials. You might use a DB structure like this:

    CREATE TABLE `baby_registry`(
    `id` INT( 11 ) NOT NULL AUTO_INCREMENT
    ,`firstname` VARCHAR( 255 ) NOT NULL
    ,`lastname` VARCHAR( 255 ) NOT NULL
    ,`date` DATETIME NOT NULL
    ,PRIMARY KEY( `id` )
    ) ENGINE=MyISAM DEFALUT CHARSET=utf8 ;

    storing a record (mysqli example):

    < ?php
    $DB = new mysqli();
    $firstname = $DB->real_escape_string( $firstname );
    $lastname = $DB->real_escape_string( $lastname );
    $SQL = "INSERT INTO `baby_registry`( `firstname`,`lastname`,`date` )
    VALUES( '$firstname','$lastname',UTC_TIMESTAMP() )";
    $DB->query( $SQL );

    retrieving a record (mysqli example):

    < ?php
    // first, tell mysql what timezone you're using
    // for timezone names, see http://php.net/manual/en/timezones.php
    $DB->query( "SET time_zone = 'America/Los_Angeles'" );
    // retrieve data
    $SQL = "SELECT `firstname`,`lastname`,`date` )
    FROM `baby_registry`
    ORDER BY `date`";
    $result = $DB->query( $SQL );
    if( $result ){
    while( $r = $result->fetch_row() ){
    list( $firstname,$lastname,$date ) = $r;
    // continue normally from here
    }
    }

    On the PHP end, avoid the mysql extension: learn mysqli (or PDO) instead.

    # May 2, 2012 at 3:08 pm

    This is a script I put together a while back. It puts stuff into the format ->

    Title, Comment, Author, Date

    extract($_POST,EXTR_SKIP);
    //list($name,$com,$author,$date)
    function CleanStr($str){
    $str = trim($str); //Remove leading and trailing whitespace
    if (get_magic_quotes_gpc()) { //magic quotes is deleted (?)
    $str = stripslashes($str);
    }

    $str = htmlspecialchars($str);//remove html special chars
    $str = str_replace("&", "&", $str);//remove ampersands

    return str_replace(",", ",", $str);//remove commas and change to special chars # THIS IS VITAL!
    }

    if($_SERVER["REQUEST_METHOD"] != "POST") error("Error: No POST.",$dest);

    // Check the contents of the form
    if(!$name||ereg("^[ |@|]*$",$name)) $name=""; // If field is empty or that unknown Jap character found...
    if(!$com||ereg("^[ |@|t]*$",$com)) $com=""; // and or a tab character...
    if(!$sub||ereg("^[ |@|]*$",$author)) $author=""; // make field empty.
    if(!$com) die("Please write something.");

    $name = CleanStr($name);
    $com = CleanStr($com);
    $author = CleanStr($author);

    $com = str_replace( "rn", "n", $com);
    $com = str_replace( "r", "n", $com);
    // Continuous lines
    $com = ereg_replace("n((!@| )*n){3,}","n",$com);
    $com = nl2br($com); //br is substituted before newline char

    $com = str_replace("n", "", $com); //delete n from a string.


    if($pass == "thisisthepassword") { // See that the password is correct

    $filename = 'logfile.txt';

    //set what will be written
    $content_r = $name.",".$com.",".$author.",".date('l jS of F Y h:i:s A')."n"; //this will write in the values on a new line separated by commas

    //write
    $file = fopen($filename,"a") or die ("Error opening file in write mode!");
    fputs($file,$content_r);
    fclose($file) or die ("Error closing file!");

    } //closing of If statement for the password.

    And this is the html form to go with it:
    (excuse the table, but it makes it all neat and tidy)










    Author:
    Password:
    Title:
    Comment:
    Everything Good?

    I hope this helps and makes a bit more sense, it works differently to the above scripts but variety in learning and techniques is always good.

    __
    # May 2, 2012 at 4:47 pm

    your script uses several ereg_* functions, which are depreciated in PHP since version 5.3, and was highly discouraged for quite some time before that.

    Additionally, using die() as an error handler is not optimal, because it leaves the user with a broken page.

    You might also look at fgetcsv(), which cleanly handles writing files in comma-separated-value format.

    # May 3, 2012 at 9:49 am

    I said I was willing but I don’t think I could figure this out between school and work. Is there another way I could go about this just as a temporary. This is the test page you will have to create a login if you want to see what I have already done. Please don’t give up on me I’ve bee trying to figure this out forever.

    If you dont want a create a login it’s
    username:cordial
    password: royalgmc
    and then go to “A sample ‘members-only’ page”

    __
    # May 3, 2012 at 10:24 am

    Not giving up on you. If you don’t have the time to work on this, you’ll need to either take your time with it, or consider hiring someone. I do freelance work like this, and I’m still willing to help if you want to try it yourself based on the examples I posted. Good luck

    # May 3, 2012 at 8:26 pm

    I had an idea, what about if I used a wordpress blog for posting the registries since I don’t have the time for the other stuff. It would be like each post was a registry and you could post and delete them whenever you wanted. Plus it would be easier on my customers employees. What do you think? Good or bad idea

    __
    # May 3, 2012 at 10:10 pm

    It’s a possible solution. I think it’s a little “overkill,” and probably would not be less work in the short term.

    But if you moved the entire site to WP (not just your “registry” page), then it could be very beneficial, especially in the long run.

Viewing 14 posts - 1 through 14 (of 14 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".