PHP Code To Do An HTML File Upload And Read In Each Line Of The File For Further Processing

Here’s an example PHP code that can handle an HTML file upload form and read in each line of the file for further processing:

<?php
if(isset($_FILES['uploaded_file'])) {
  $errors = array();
  $file_name = $_FILES['uploaded_file']['name'];
  $file_size = $_FILES['uploaded_file']['size'];
  $file_tmp = $_FILES['uploaded_file']['tmp_name'];
  $file_type = $_FILES['uploaded_file']['type'];
  $file_ext = strtolower(end(explode('.',$_FILES['uploaded_file']['name'])));
  
  $extensions = array("txt");
  
  if(in_array($file_ext,$extensions)=== false){
     $errors[]="Extension not allowed, please choose a TXT file.";
  }
  
  if($file_size > 2097152) {
     $errors[]='File size must be less than 2 MB';
  }
  
  if(empty($errors)==true) {
     $file = fopen($file_tmp, "r");
     while(!feof($file)) {
       $line = fgets($file);
       // do something with the line, e.g. process it or store it in a database
       echo $line;
     }
     fclose($file);
     echo "Success";
  }else{
     print_r($errors);
  }
}
?>

<html>
<body>

<form action="" method="POST" enctype="multipart/form-data">
  <input type="file" name="uploaded_file" />
  <input type="submit"/>
</form>

</body>
</html>

This code opens the uploaded file for reading and reads in each line using fgets(). It then processes each line as needed (e.g. storing it in a database), and displays “Success” once all lines have been processed. Note that in this example, we’re assuming the uploaded file is a text file (hence the “txt” extension), but you can modify the $extensions array to allow other file types as needed.

Leave a Reply

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.