PHP
June 3, 2026 2 min read

File Upload in PHP: Step-by-Step Guide

HS
HEMANT SINGH
Technical Writer & Educator
<!DOCTYPE html>
<html>
<head>
 <title>File upload in php</title>
</head>
<body>
 <?php 
 if(isset($_POST['upload'])){
 // we will upload file when this variable has value false
 $uploadError=false; 
 // Getting file name
 $file_name=$_FILES['photo']['name'];
 // Getting temporary name
 $file_tmp_name=$_FILES['photo']['tmp_name'];
 // Getting file size, by default file size in byte then we are converting in Mega bytes.
 $file_size=$_FILES['photo']['size']/(1024*1204); 
 // path where upload file will store
 $path="images/$file_name"; 
 // Getting extension of file
 $extension=pathinfo($path, PATHINFO_EXTENSION);
 // Only jpg, png files are allowed
 if($extension!="jpg" && $extension!="png"){
 $uploadError=true;
 echo "Only jpg, png files are allowed.<br>";
 } 

 // Only less than 1 MB size files are allowed
 if($file_size>1){
 $uploadError=true;
 echo "Only less than 1mb files allowed.<br>";
 }

 // If there is no error ($uploadError has value false)
 if(! $uploadError){
 move_uploaded_file($file_tmp_name, $path);
 echo "Photo uploaded successfully.<br>";
 }
 else{
 echo "Something wrong, please correct all errors.<br>";
 }
 }
  ?>

 <fieldset>
 <legend>Upload File</legend>
 <!-- Form tag must have enctype attribute -->
 <form action="first.php" method="POST" enctype="multipart/form-data">
 <p>
 <label for="photo">Select photo</label>
 <!-- Make sure input tag type attribute has value file  -->
 <input type="file" name="photo">
 </p>

 <p>
 <input type="submit" name="upload" value="Upload">
 </p>

 </form>
 </fieldset>

</body>
</html>