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

CodingStatus

- Learn Coding to Build Web Applications

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

File Upload in PHP with Example & Code Demo

January 1, 2023 By Md Nurullah Leave a Comment

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

 

Contents

  • How to Upload File in PHP
    • 1. Create an HTML  Form
    • 2. Write PHP File Upload Script
    • My Suggestion

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:

  • PHP Interview Questions and Answers
  • Javascript Interview Questions and Answers for Freshers &…
  • Upload Multiple Files to Store in MySQL Database Using PHP
  • Upload Multiple Files Using Multer in Node.js and Express

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 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Follow us

  • facebook
  • twitter
  • linkedin

Latest Tutorials

  • HTML Heading Tags
  • Compress Image Size in PHP Without Losing Quality
  • How to Trigger a Click Event on Pressing Enter Key Using jQuery
  • HTML Elements
  • JavaScript Countdown Timer

Popular Tutorials

  • Compress Image Size in PHP Without Losing Quality
  • File Upload in PHP with Example & Code Demo
  • PHP Form Validation with example
  • PHP Registration Form
  • Default Profile Picture From First Name and Last Name in PHP

Categories

  • Ajax (10)
  • Django (5)
  • HTML (4)
  • Interview Questions (5)
  • JavaScript (18)
  • jQuery (11)
  • Laravel (2)
  • Node.js (22)
  • PHP (39)
  • ReactJS (35)
  • SQL (12)
  • Tips (7)
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved