0

I am trying to upload a txt file to MYSQL database periodically as the txt file contents changes with time. I have 2 files: db.php and uploader.php. Below is the code for db.php

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="uploader.php" method="post"
                        enctype="multipart/form-data">
<input type="file"  onchange="this.form.submit()" name="file"  size="50" />
<br /> 
</form>
</body>
</html>

And the code for uploader.php

<?php
$contents = file_get_contents($_FILES['file']['tmp_name']) 
or die( "Could not copy file!");

$username = "username";
$password = "password";
$hostname = "localhost";

//connection to the database
$connection=mysql_connect ($hostname, $username, $password)
or die("Unable to connect to MySQL");

//select a database to work with
$selected = mysql_select_db("test",$connection)
or die("Could not select examples");

$result2 = mysql_query("INSERT INTO testtable(data) VALUES (". $contents. ")");
mysql_close($connection);
?>

Upon running the program, I have to browse for my txt file and will be redirected to uploader.php. Data is then sent to my database. As data is being written to the txt file in my pc periodically, I need to upload the file to my database again automatically without the need to browse for the txt file again. The question is, how can I do that? If I were to manually refresh the webpage periodically, the new data will be sent to my database but of course, I wouldn't want to manually refresh the page as it is impractical. I tried adding <META HTTP-EQUIV="refresh" CONTENT="5"> which refreshes the page every 5s but this does not work

I am very new to php so I would really appreciate if the answers are simple and easy to understand. Thank you very much for your help.

Phil
  • 157,677
  • 23
  • 242
  • 245
Sakuya
  • 11
  • 3
  • 1
    Why don't you just have whatever process is writing to the file also write to the database? Doing this sort of thing via a web form seems very wrong – Phil Mar 04 '15 at 00:35
  • What is writing to the text file? You could always have it write directly to the database. Otherwise you're kind of stuck with how I see it unless if the database is hosted on the same computer as the file. – Matt Shirley Mar 04 '15 at 00:35
  • @Phil Correct me if I am mistaken, I googled quite a bit and it seems the only way to access a local file (in my laptop C drive) and send it to the server is by using web form. – Sakuya Mar 04 '15 at 00:39
  • @MattShirley The hardware that is writing to the text file does not have a wifi connection. – Sakuya Mar 04 '15 at 00:42
  • What if my txt file contain hazardous substance that can lead to sql injection ? You shall alway use `mysqli_` .and pass data through your `_escape_string` – frunkad Mar 04 '15 at 01:03
  • 1
    And for you problem - use client side Python or Java etc to send data – frunkad Mar 04 '15 at 01:04

3 Answers3

3

The problem you are hitting is, that the HTML form interface of a browser was designed to be interacted with by humans - but you want it to interact with a timer or similar mechanism.

So basically, you have to replace the browser by something, that can easily be automated - I recommend you use wget:

  • Use a shell script, a client-side PHP, or whatever is available to you to create the POST data
  • use wget --method=POST --post-data="$POST" http://your.domain/and.url to transfer
  • use cron to set this up automatically
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • I ran 'wget --method=POST --post-data="$POST" http://my.domain/and.url' in my command prompt and got an error stating wget: unrecognized option '--method=POST'. – Sakuya Mar 04 '15 at 01:08
  • Didn't actually know `wget` could post data. I'd probably just use `curl` to send the file instead of creating a POST data string – Phil Mar 04 '15 at 01:09
  • @Sakuya Maybe you have a different version of `wget` - try leaving this option out – Eugen Rieck Mar 04 '15 at 01:09
  • @Phil I recommended `wget` over `curl` because it is easier and has a nice windows port. I personally would use `curl` also. – Eugen Rieck Mar 04 '15 at 01:10
  • @Phil How do I use curl to send the local txt file to the browser? i.e What do I have to type in the command prompt? Thanks in advance – Sakuya Mar 04 '15 at 10:35
  • @Sakuya not to the browser, to your PHP script – Phil Mar 04 '15 at 22:52
0

This is not a full solution. It is just an example to show how to repeat the form submit every nn seconds. See important notes at bottom, and then consider Eugen Rieck's solution.

To do what you are asking, you can use javascript/jQuery. The code would look like this:

<html>
<head>
    <title>File Uploading Form</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            setTimeout(function(){
                myTimeoutFunction();
            },100000); //delay 100 seconds before first submit
        });
        myTimeoutFunction(){
            $('form').submit();
            setTimeout(myTimeoutFunction, 1000000); //repeat every 100 seconds
        }
    </script>
</head>
<body>
    <h3>File Upload:</h3>
    Select a file to upload: <br />
    <form action="uploader.php" method="post" enctype="multipart/form-data">
        <input type="file"  onchange="this.form.submit()" name="file"  size="50" />
        <br /> 
    </form>
</body>
</html>

Notes:

  1. This will require that the browser remain open on this web page. As soon as the page / browser is closed, this will stop working.

  2. As you see, a user must select the file each time.

  3. Load the jQuery library in the <head>

  4. Call the jQuery submit() method to submit the form programmatically

  5. Wrap that in a setTimeout to delay nn ms between re-submits

Reference:

setTimeout or setInterval?

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • Thank you for the help. I need it to work such that the user only selects the file once and data will be sent periodically. – Sakuya Mar 04 '15 at 01:44
0

I think you could use javascript/jquery to repeat the form upload every x seconds.

<body>
<head>
    <script src="https://code.jquery.com/jquery-2.1.3.js"></script>
</head>
<h3>File Upload:</h3>
Select a file to upload:
<br />
<form id="upload-form" action="uploader.php" method="post" enctype="multipart/form-data">
    <input type="file" onchange="this.form.submit()" name="file" size="50" />
    <br />
</form>

<script>
    /*
     * On form submission we will use an ajax request to submit the form, then if the ajax request is successful we will resubmit the form every 60 seconds.  Not sure if the file that is being uploaded will be changed if the filesystem changes.
     */
    $('#upload-form').submit(function (e) {
        e.preventDefault();
        var form = $('#upload-form'),
            formData = new FormData(form.get(0));

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: formData,
            processData: false,
            contentType: false
        }).done(function (response) {
            setTimeout($('#upload-form').submit(), 60000);//Resubmit form every 60 seconds
            console.log('File Uploaded Successfully');
        }).fail(function (jqXhr) {
            alert('File Upload failed for some reason');
            console.error('File Upload Failed');
        }).always(function() {
        });

        return false;
    });
</script>
</body>
A. J. Parr
  • 7,731
  • 2
  • 31
  • 46
  • Thank you for your help. I tried running the code, however, it doesn't seem like the form is being resubmited automatically every 60sec as there is no new data being sent to my database every 60s. – Sakuya Mar 04 '15 at 01:41