Skip to content
Advertisement

PHP, Image preview with javascript and uploader by PHP

I made PHP script to preview an image before upload it, which is simple and easy to read. the first part is to displays the image then to upload it after pressing Submit button. I have an issue with uploading the image, it doesn’t upload.

<?php
if (!empty($_POST["uploadForm"])) {
if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
    $targetPath = "uploads/".$_FILES['userImage']['name'];
    if (move_uploaded_file($_FILES['userImage']['tmp_name'], $targetPath)) {
        $uploadedImagePath = $targetPath;
    }
  }
}
?>
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="userImage" />
<script>
var loadFile = function(event) {
    var output = document.getElementById('userImage');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {URL.revokeObjectURL(output.src) } // free memory
};
</script>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
   <input type="submit" name="upload" value="Submit" class="btnSubmit">
</form>

Advertisement

Answer

You have several logical errors in your PHP Code as well as HTML.

  1. When checking for form submission you have to check if “upload” (name of submit button) is in the $_POST.
  2. The File Upload Input should be inside <form> tag.
  3. Set a name for File Upload field, I have set it to “userImageUpload”, so you can access it from $_FILES in PHP.

Here is the final Code:

<?php
if (!empty($_POST["upload"])) {
    if (is_uploaded_file($_FILES['userImageUpload']['tmp_name'])) {
        $targetPath = "uploads/" . $_FILES['userImageUpload']['name'];
        if (move_uploaded_file($_FILES['userImageUpload']['tmp_name'], $targetPath)) {
            $uploadedImagePath = $targetPath;
        }
    }
}
?>

<img id="userImage" />
<script>
    var loadFile = function(event) {
        var output = document.getElementById('userImage');
        output.src = URL.createObjectURL(event.target.files[0]);
        output.onload = function() {
            URL.revokeObjectURL(output.src)
        } // free memory
    };
</script>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
    <input type="file" accept="image/*" onchange="loadFile(event)" name="userImageUpload">
    <input type="submit" name="upload" value="Submit" class="btnSubmit">
</form>

Note: Please make sure that “upload” folder is already there and permissions are correct too.

8 People found this is helpful
Advertisement