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.
- When checking for form submission you have to check if “upload” (name of submit button) is in the $_POST.
- The File Upload Input should be inside <form> tag.
- 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.