File upload using PHP

In this post, I will show how to upload files like image,document and other type of files using php script . You can upload any kind of files and also can validate them while uploading.

First of all you need to increase the value of upload_max_filesize and post_max_size in your php.ini. This is require when your uploaded file size is greater than default value of post_max_size. Suppose default value of upload_max_size is 2M and your file is greater than 2M then it will produce error.After that restart the server.

Finally the code of files uploading.Please find below.

Upload.php

<?php
/*-------------Script For Uploading ----------------------*/
if(isset($_POST['upload'])){
$file_name=$_FILES['myfile']['name'];
$temp_file=$_FILES['myfile']['tmp_name'];
$file_size=$_FILES['myfile']['size'];
$new_file=uniqid().'_'.$file_name;
$store='upload/'.$new_file;  /*// Upload Path//*//
$extension=explode('.',$file_name);
$extension=end($extension);
if($extension=='doc'|| $extension=='docx'|| $extension=='png'){ /*//validating File Type//*/
if($file_size<=9000000){ /*//validating File size//*/
move_uploaded_file($temp_file,$store);
echo '<script>alert("File Uploaded successfully");</script>';
}else{
echo '<script>alert("File size should not greater then 9 MB");</script>';
}
}else{
echo '<script>alert("Please upload valid file");</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
h3{
font-family: Verdana;
font-size: 18pt;
font-style: normal;
font-weight: bold;
color:red;
text-align: center;
}
table{
font-family: Verdana;
color:black;
font-size: 12pt;
font-style: normal;
font-weight: bold;
text-align:left;
border-collapse: collapse;
}
.error{
    color:red;
  font-size: 11px;
}
</style>
<h3>File Upload Example</h3>
<formmethod="post"enctype="multipart/form-data"action="">
    <table align="center" cellpadding = "5">
        <tr>
            <td>File</td>
            <td><input type="file" name="myfile" ></td>
            
        </tr>
        <tr>
            <td colspan="5" align="center">
            <input type="submit" value="Upload" name="upload"/></td>
        </tr>
    </table>
</form>
</body>
</html>

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!

I am Hitesh from Jamshedpur (India). I have been working as a Web Application Developer from last 4+ years. I love diverse and attention catching web presence for a variety of users. Also I love to learn new things in Web Development.