• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar

CodingStatus

- Free Source Code for Web Applications

  • programs
  • JavaScript
  • jQuery
  • ReactJS
  • Ajax
  • Node.js
  • PHP
  • SQL
  • Interview Questions

File Upload in PHP with Example & Code Demo

January 1, 2023 By Md Nurullah

File Upload in PHP: If you want to upload a single file at a time using PHP. This tutorial will be helpful. You will get a general script within a custom function. This function can be used in multiple pages.

File Uploading is the most important part of the form. Because, In many cases, Users need to upload their required files to the website. So, PHP has provided us simple way to upload files by writing a few lines of the code.

Using this PHP file upload Script, You can upload different types of files like jpg, png, gif type image upload, pdf, doc, PHP, Html, CSS, zip, txt, excel, CSV, etc.

File upload in php

 

How to Upload File in PHP

Before Starting Coding, You should create the following folder structure. Otherwise, you can use the given file upload script directly in your project.

myproject
   |__uploads/
   |__upload-form.php
   |__upload-script.php
   |

 

Read Also

Create Registration Form Using PHP

PHP Form Validation with Example

Now, Configure the following steps. It is easy to understand & implement in  a project

1. Create an HTML  Form

  • First, Create an Upload form with the following attribute
  • method=post – It sends the form data with security.
  • enctype="multipart/form-data" – This attribute allows us to upload all types of files such as images, videos, pdfs, docs, etc.
  • action="upload-script.php" It will redirect to upload-script.php to execute the PHP script of file uploading. Don’t worry, It will explain in the next step.
  • type="file" It is necessary to select a file from the computer.

File Name – upload-form.php

<form method="post" enctype="multipart/form-data" action ="upload-script.php">
<input type="file" name ="file">
<input type="submit" name="submit">
</form>

2. Write PHP File Upload Script

To write the PHP file script, read all the following points

  • First, the check file is set or not using $_POST['submit']  within if statement.
  • If it is set. Call upload_file() and store in $msg variable
  • Start session & store $msg in a session, variable to display success or error message after uploading the file.

upload_file() Method

This method containing the following steps

  • Declares a folder name where you have to save the file.
  • Allow file type to upload.
  • Get filename using $_FILES['file']['name'] and temporary file path using $_FILES["file"]["tmp_name"]
  • Get the type of selected file.
  • If the selected file type is matched with the allowed file type, move the file from a temporary path to the original path using move_uploaded_file() to upload the file.
  • If the file will be uploaded successfully, return a success message. otherwise, return an error message.

File Name – upload-script.php

<?php

// uploading files on submit
if(isset($_POST['submit'])){ 
  
    //  uploading files
    $msg= upload_file(); 
    session_start();
    $_SESSION['msg']= $msg;
    header('location:upload-form.php');

}


function upload_file(){

    $uploadTo = "uploads/"; 
    $allowFileType = array('jpg','png','jpeg','gif','pdf','doc');
    $fileName = $_FILES['file']['name'];
    $tempPath=$_FILES["file"]["tmp_name"];
   


    $basename = basename($fileName);
    $originalPath = $uploadTo.$basename; 
    $fileType = pathinfo($originalPath, PATHINFO_EXTENSION); 

    if(!empty($fileName)){ 
    
       if(in_array($fileType, $allowFileType)){ 

         // Upload file to server 
         if(move_uploaded_file($tempPath,$originalPath)){ 

            return $fileName." was uploaded successfully";

           // write here sql query to store image name in database
          
          }else{ 
            $error = 'File Not uploaded ! try again';
          } 
      }else{
         return $fileType." file type not allowed";
      }
   }else{  
    return "Please Select a file";
   }       

}
?>

 

This code will work when you select a file from your computer and click the submit button. This code can only upload a file to a folder. You want to upload to the database as well then you will have to write SQL code within the line of code where the file will be uploaded successfully.

Now, You can use this code in your project if you want to provide a feature to upload a single file at a time. You can also set the file type according to the project requirement.

My Suggestion

I have provided the above source code. I hope, this tutorial will be helpful for you. If you have any doubt or questions, ask me directly through the comment box. I will definitely reply as soon as possible.

Related posts:

  1. How to Create Multilevel Category in PHP MySQL
  2. PHP Contact Form with Sending Email
  3. Display Data in an HTML Table Using PHP & MySQL
  4. Approve And Disapprove in Ajax, PHP & MySQL

Filed Under: PHP

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Primary Sidebar

Latest Tutorials

  • Login with ajax in PHP, MySQL
  • Load Records on Select Box using Ajax, PHP & MySQL
  • Swapping of Two Numbers in python
  • How to Install Express Application Using Express Generator Tool
  • Registration Form using Ajax, PHP & MySQL

Popular Tutorials

  • Filter Data with Checkboxes in PHP & MySQL
  • Filter Data by Category in PHP & MySQL
  • Filter Prices From Low to High in PHP, MySQL
  • To Do List Using PHP and MySQL
  • Upload Multiple Files to Store in MySQL Database Using PHP

Categories

  • Ajax (12)
  • Django (5)
  • HTML (4)
  • Installation (3)
  • Interview Questions (5)
  • JavaScript (20)
  • jQuery (11)
  • Laravel (2)
  • Node.js (23)
  • PHP (42)
  • programs (1)
  • Python Programs (1)
  • ReactJS (35)
  • SQL (12)
  • Tips (7)
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved