Search code examples
phpmysqldatabasetexttext-files

Upload .txt file and insert contents into a database


I am trying to grab the contents of a text file, verify that there are 60,000 characters or less, and insert that into a database. If there are more than 60,000 characters it should be truncated.

How can I achieve this?


Solution

  • <?php
    
    // db connection here
    
    // set path of uploaded file
    $path = "./".basename($_FILES['filename']['name']); 
    
    // move file to current directory
    move_uploaded_file($_FILES['filename']['tmp_name'], $path)) {
    
    // get file contents
    $data = file_get_contents($path, NULL, NULL, 0, 60000);
    
    // run the query
    @mysql_query("INSERT INTO table (column) VALUES ('".$data."')");
    
    // delete the file
    unlink($path);
    
    ?>
    <form enctype="multipart/form-data" action="" method="POST">
      <input name="filename" type="file" /><br />
      <input type="submit" value="upload file" />
    </form>