File Upload in PHP

Hello All,

I had to make a custom form for file uploading in PHP, I am explaining here the way to upload a file.

<?php
//error_reporting(E_ALL); 
if(isset($_FILES) && !empty($_FILES['docname']))
{
    
    $target_dir = "../tmp/";
    $target_file = $target_dir . basename($_FILES["docname"]["name"]);
    $isUploaded = 1;
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $isUploaded = 2;
    }
    
    // Check if $isUploaded is set to 2 
    if ($isUploaded == 2) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["docname"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["docname"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>
<form id="doc-form" name="doc-form" method="post" action="" enctype="multipart/form-data">
<label>Upload Document</label>
<input type="file" title="file" name="docname">
<input type="submit" value="Upload file" id="Submit" />                    
</form>

Leave a Reply

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

Scroll to top