How to upload file in php with example demo

In this tutorial we are going learn PHP file Upload with error handling. file upload is most require for any web app whether it’s profile image upload, documents or any other docs. In this tutorial we can cover simple file upload form with validation and store data inside DB.

Let’s have begin with configuration file.

Configure php.ini file
; Whether to allow HTTP file uploads.
file_uploads = On

Create basic file upload form where user can select image.

  • enctype ="multipart/form-data" require attributes for upload file.
Create Simple HTML File Upload Form
  <form action="upload.php" method="POST" enctype ="multipart/form-data">
    <input type="file" name="file_name" />
    <input type="submit" name="upload"/>
  </form>

Create upload.php file

On form submit button handle the file upload, validations and store inside directory.

  • allow only specific extensions file like jpeg, jpg, png.
  • less then 5M size image allow.
  • Create image directory and make sure 777 permission.
<?php
   if(isset($_FILES['file_name'])){
      $errors= array();
      $file_name = $_FILES['file_name']['name'];
      $file_size = $_FILES['file_name']['size'];
      $file_tmp = $_FILES['file_name']['tmp_name'];
      $file_type = $_FILES['file_name']['type'];
      $file_array=explode('.',$_FILES['file_name']['name']);
      $file_ext=strtolower(end($file_array));
      
	  
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 500000) {
         $errors[]='Sorry, your file is too large';
      }
      
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>

move_uploaded_file(string $from, string $to): bool — Moves file to a new location

from : The filename of the uploaded file.
to : The destination of the moved file.

Store file in Database.

If you want to store uploaded file in database, below simple code will help you. let’s begin with create database table.

CREATE TABLE `image_upload` (
  `id` int(11) NOT NULL,
  `image_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
	
ALTER TABLE `image_upload` ADD PRIMARY KEY (`id`);
ALTER TABLE `image_upload` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Create database connection ( Config.php )
define("DB_HOST", "localhost"); 	// Database Host
define("DB_USER", "root");  		// Database Username
define("DB_PASS", "");				// Database Password
define("DB_NAME", "database_name_of_your"); 	// Database Name

// Database Connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);

// Check The Connection
if (mysqli_connect_errno() ){
	echo "Database Connection Failed: " . mysqli_connect_error();
	die;
}

mysqli_set_charset($connection,"utf8");

Let’s create code for Upload image and save in MySQL Database

  • Include database connection file.
  • Create image directory
  • Add validation for image size and extensions.
  • Use move_uploaded_file() to upload in image directory
  • Insert image name in MySQL DB.
Update MySQL insert code on Upload.php
      include('config.php');
      if(isset($_FILES['file_name'])){
        $errors= array();
        $file_name = $_FILES['file_name']['name'];
        $file_size = $_FILES['file_name']['size'];
        $file_tmp = $_FILES['file_name']['tmp_name'];
        $file_type = $_FILES['file_name']['type'];
	$file_array=explode('.',$_FILES['file_name']['name']);
        $file_ext=strtolower(end($file_array));
        $extensions= array("jpeg","jpg","png");
      
        if(in_array($file_ext,$extensions)=== false){
           $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }
      
        if($file_size > 500000) {
           $errors[]='Sorry, your file is too large';
        }
      
        if(empty($errors)==true) {
           if(move_uploaded_file($file_tmp,"images/".$file_name)){
			 mysqli_query($connection,"INSERT into image_upload (image_name) VALUES ('".$file_name."')");
			 echo "Success";
           }
         
        }else{
           print_r($errors);
        }
   }
Conclusion.

We are discuss file upload using PHP with add validations and store file data inside MySQL. upload directory permission should be 777.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply