How to upload file in php with example demo

PHP file Upload with error handling. when you dealing with file upload process, sometime that stuck for some reasons like invalid file formats, server handling, file size is bigger etc… so in this tutorial we are implement all error handling when user upload file. We will add validation to stop this invalid activities.

Let’s have begin with configuration file.

Configure php.ini file

; Whether to allow HTTP file uploads.
file_uploads = On

PHP Upload file Code.

We are start with simple upload file when user select file and click on submit button to store inside project directory. create image folder and index.php file inside root of the directory.

  • allow only specific extensions file like jpeg, jpg, png.
  • less then 5M size image allow.
<?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);
      }
   }
?>
<html>
   <body>
      
      <form action="" method="POST" enctype ="multipart/form-data">
		<input type="file" name="file_name" />
		<input type="submit"/>
		
		<?php if(isset($_FILES['file_name'])){	 ?>
         <ul>
            <li>Sent file: <?php echo $_FILES['file_name']['name'];  ?>
            <li>File size: <?php echo $_FILES['file_name']['size'];  ?>
            <li>File type: <?php echo $_FILES['file_name']['type'] ?>
         </ul>
		<?php } ?>
      </form>
      
   </body>
</html>

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.

Saved in Database

Save image inside database. This code is useful when you dealing with real life project so, let’s create the database TABLE in MySQL.

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 Connection file.

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.

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.

This tutorial we are implement the file upload using PHP and MySQL. We seen store image in database and simple upload process.

Comments

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

    Leave a Reply