Sunday 24 November 2013

Read text file contents line by line

The following example shows, how to upload text file and read that uploaded file.And also insert the line by line text file contents  to MySQL Database.

Create a folder in your root, Here we named it as upload.In this folder we are uploading text file.

In you form html

    <html>
    <body>
    <table align="center">
    <form action="upload_page.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
    </form>
    </table>
    </body>
    </html>

And your upload_page.php

    <?php
    //upload file to upload folder
    $uploaddir = 'upload/';
    $uploadfile = $uploaddir . basename($_FILES['file']['name']);
    //if upload is success
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    //read file
    $fp = fopen($uploadfile, 'rb');
    while ( ($line = fgets($fp)) !== false) {
    echo $line.'<br />';
    }
    } else {
    echo "Error in file upload";
    }
    ?>

No comments:

Post a Comment