Today i will show you how to upload files with PHP in very simple steps. PHP make simple to upload files to the server. Thus we need to be careful enough while uploading file because anyone can upload any malicious script to bring our server down or even worse.

Whenever the user submits the data, first the uploaded file goes to the ‘tmp’ directory and then with this command we can transfer the file from the ‘tmp’ directory to wherever we want.


move_uploaded_file();

First let’s start with creating and upload form.

<pre><title>PHP File Upload</title>
<style>
    form{
        width: 300px;
        box-sizing: border-box;
        padding: 20px;
        background: #e3dfd7;
        border-radius:10px;
        margin: 150px auto;
    }
    form input
    {
        margin-bottom: 10px;
    }
    form input[type="file"]{
        width: 100%;
        padding: 10px;
        font-size: 18px;
    }
    form input[type="submit"]
    {
        width: 100%;
        border-radius: 10px;
        border:0px;
        background: #33691e;
        color:white;
        padding: 10px;
        font-size: 18px;
    }
    #message
    {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        box-sizing: border-box;
        padding: 10px;
        color: white;
        background: #64dd17;
        text-align: center;
    }
</style>

<form method="POST" enctype="multipart/form-data"> // enctype is important!!
    <h1>Upload File</h1>
    <input type="file" name="file">
    <br>
    <input type="submit">
</form></pre>

 

so now we are ready with our html form page. Now here is the php script to upload files.

<?php
   
    if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_FILES['file']['name'])){
        $filename = $_FILES['file']['name'];
        if(strpos($filename,'.php') == true) // If file is a php
        {
            header('location:index.php?msg=1');
        }
        else{
            $dir='uploads/'.$filename;
            if(file_exists($dir) == true) // To check if the file exist
            {
                $filename = uniqid().$filename; //if file exist..we rename so that it cannot replace existing file.
            };
            move_uploaded_file($_FILES['file']['tmp_name'],'uploads/'.$filename);
            header('location:index.php?msg=2');
        };
    };
if(isset($_GET['msg']) && !empty($_GET['msg'])){
    if($_GET['msg'] == 1){
        echo "<div id='message' style='background: red'>Upload Failed!! </div>";
    };
    if($_GET['msg'] == 2){
        echo "<div id='message' > Uploaded Sucessfully!! </div>";

    };
};
?>

So now you are ready to upload files.

* Tip . To get the file size and type.. you can use $_FILES[‘file’][‘size’] and $_FILES[‘file’][‘type’]

Download A sample Project Here.

Advertisements