简体   繁体   中英

PHP Image Upload Is Not Uploading Image to target directory

Problem:

I have created a upload.php file, which contains a HTML form and the PHP code needed to upload images and I use XAMPP localhost:

htdocs/web2/assets/upload.php

I want to upload images to the folder upload in the same directory:

htdocs/web2/assets/uploads/

Script:

    <?php 

        <form action="?" method="post" enctype="multipart/form-data">   

            <!--wrap input button as around pre-existing image -->   
            <?php
                echo '<label class="profile_gallery_image_in"><input type="file" name="fileToUpload" id="fileToUpload" onchange="form.submit()"/><p class="label"></p><img class="myImg" src='.$image.' height="100%" width="100%" /></label>';
            ?>

        </form>

    <!-- Commence Photo Upload -->

    <?php
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                echo "File is not an image.";
                $uploadOk = 0;
            }
        }
    ?>

The form is set to auto-submit upon input type change. This appears to be working fine and the form is submitting.

However, I get no actual image uploaded and no error at all.

How do I solve this problem?

There seems to be an error in the code. You can use the below code for image uploading.

 <?php if(isset($_FILES['image'])){ $errors= array(); $dir = "images/"; $file_name = $_FILES['image']['name']; $file_name = $dir. $file_name; $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; $file_type = $_FILES['image']['type']; $tmp = explode('.',$_FILES['image']['name']); $file_ext=strtolower(end($tmp)); $extensions= array("jpeg","jpg","png","gif"); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a GIF, JPEG or PNG file."; } if($file_size > 2097152) { $errors[]='File size must be excately 2 MB'; } if(empty($errors)==true) { move_uploaded_file($file_tmp, $file_name); echo "Success"; }else{ print_r($errors); } } ?> <html> <body> <form action = "" method = "POST" enctype = "multipart/form-data"> <input type = "file" name = "image" /> <input type = "submit"/> </form> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM