File Uploading in PHP

Last updated on Oct 05 2022
Aridam Das

Table of Contents

File Uploading in PHP

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps −

  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form’s action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.

An uploaded file could be a text file or image file or any document.

Creating an upload form

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

 

<?php   
if(isset($_FILES['image']))
{      
$errors= array();      
$file_name = $_FILES['image']['name'];      
$file_size =$_FILES['image']['size'];      
$file_tmp =$_FILES['image']['tmp_name'];      
$file_type=$_FILES['image']['type'];      
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));            
$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 > 2097152)
{         
$errors[]='File size must be excately 2 MB';      
}            
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="image" />         
<input type="submit"/>      
</form>         
</body>
</html>

php 11

Creating an upload script

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input’s name attribute in uploading form was file, then PHP would create following five variables −

  • $_FILES[‘file’][‘tmp_name’] − the uploaded file in the temporary directory on the web server.
  • $_FILES[‘file’][‘name’] − the actual name of the uploaded file.
  • $_FILES[‘file’][‘size’] − the size in bytes of the uploaded file.
  • $_FILES[‘file’][‘type’] − the MIME type of the uploaded file.
  • $_FILES[‘file’][‘error’] − the error code associated with this file upload.

Example

Below example should allow upload images and gives back result as uploaded file information.

<?php   if(isset($_FILES['image']))
{      
$errors= array();      
$file_name = $_FILES['image']['name'];      
$file_size = $_FILES['image']['size'];      
$file_tmp = $_FILES['image']['tmp_name'];      
$file_type = $_FILES['image']['type'];      
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));            
$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 > 2097152) 
{         
$errors[]='File size must be excately 2 MB';      
}            
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 = "image" />        
<input type = "submit"/>                                                       
<ul>            
<li>Sent file: 
<?php echo $_FILES['image']['name'];  
?>            
<li>File size: 
<?php echo $_FILES['image']['size'];  
?>            
<li>File type: 
<?php echo $_FILES['image']['type'] 
?>         
</ul>                                                    
</form>         
</body>
</html>

It will produce the following result −

php 12

PHP – Coding Standard

Every company follows a different coding standard based on their best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.

Here are several reasons why to use coding specifications −

  • Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code.
  • Simplicity and clarity achieved by consistent coding saves you from common mistakes.
  • If you revise your code after some time then it becomes easy to understand that code.
  • Its industry standard to follow a particular standard to being more quality in software.

There are few guidelines which can be followed while coding in PHP.

  • Indenting and Line Length − Use an indent of 4 spaces and don’t use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability.
  • Control Structures − These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional.

Examples

if ((condition1) || (condition2)) {

   action1;

}elseif ((condition3) && (condition4)) {

   action2;

}else {

   default action;

}

You can write switch statements as follows −

switch (condition) {

   case 1:

      action1;

      break;

  

   case 2:

      action2;

      break;

        

   default:

      defaultaction;

      break;

}
  • Function Calls − Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here’s an example −

$var = foo($bar, $baz, $quux);

  • Function Definitions − Function declarations follow the “BSD/Allman style” −
function fooFunction($arg1, $arg2 = '') {

   if (condition) {

      statement;

   }

   return $val;

}
  • Comments − C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.
  • PHP Code Tags − Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups.
  • Variable Names
    • Use all lower case letters
    • Use ‘_’ as the word separator.
    • Global variables should be prepended with a ‘g’.
    • Global constants should be all caps with ‘_’ separators.
    • Static variables may be prepended with ‘s’.
  • Make Functions Reentrant − Functions should not keep static variables that prevent a function from being reentrant.
  • Alignment of Declaration Blocks − Block of declarations should be aligned.
  • One Statement Per Line − There should be only one statement per line unless the statements are very closely related.
  • Short Methods or Functions − Methods should limit themselves to a single page of code.

There could be many more points which should be considered while writing your PHP program. Over all intention should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. You can device your own standard if you like something different.

So, this brings us to the end of blog. This Tecklearn ‘File Uploading in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "File Uploading in PHP"

Leave a Message

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