File upload using PHP

Today we learn how to upload the file using PHP. The file upload is too easy using PHP. The file upload is very common functionality even you developed the small project you need to add the file uploading functionality. so let’s see how to upload the file using PHP. For file upload using PHP follow below steps.

First, create the “index.html” file.

<!DOCTYPE html>
<html>
<head>
    <title>The Coding Stuff - PHP - File Upload</title>
</head>
<body>
    <form action="fileupload.php" method="POST" enctype="multipart/form-data">
        <p>
            Select File to upload:
        </p>
        <p>
            <input type="file" name="fileupload" id="fileupload">
        </p>
        <input type="submit" value="Upload Image" name="submit">
    </form>
</body>
</html>

Second, create the “index.php” file with below content.

<?php
if( $_POST['submit'] ){
    $file_name = $_FILES['fileupload']['name'];
    
    // commenth below code if you don't want to change the file name
    $fileNames = explode(".",$file_name);
    $file_name = time().".".$fileNames[count($fileNames) - 1];

    $file_upload = move_uploaded_file($_FILES['fileupload']['tmp_name'],"uploads/".$file_name);
    if( $file_upload ) {
        echo "File uploaded successfully";
        echo "<p>";
             echo "<img src='uploads/$file_name' style='width:100px;height:100px;'/>";
        echo "</p>";
    } else {
        echo "Errors #".$_FILES["file"]["error"];
    }
}
?>

If you face any issue after using above code or need any kind of help please write a comment below.