首页 > 解决方案 > PHP将多个图像上传到目录 - 失败

问题描述

所以我有这个正在工作的脚本,它将图像上传到正确的目录(我创建的)并将图像放入该目录并重命名它们,酷!但是,我放置的小显示错误文本总是打印每一个错误。因此,例如我有 $j++ 并且我的错误最多将有 $j = 4 并且如果 $j = 4 那么所有错误都会打印出来,你会假设有问题并且图像还没有上传。但是我选择了 4 张图片,其中 3 张上传了,但仍然显示所有错误。

所以我的问题是,到底为什么会显示所有错误以及为什么只有四分之三的图片上传?我希望能够一次上传 30 张图片...

代码

    //Image Upload Section

$j = 0; //Variable for indexing uploaded image 

    $target_path = $imagePath."/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path.md5(uniqid()).
        ".".$ext[count($ext) - 1]; //set the target path with a new name of image
        $j = $j + 1; //increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < 100000000) //Approx. 100000kb files can be uploaded.
            && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
                echo $j.
                ').<span id="noerror">Image Uploaded Successfully!.</span><br/><br/>';
            } else { //if file was not moved.
                echo $j.
                ').<span id="error">Please Try Again!.</span><br/><br/>';
            }
        } else { //if file size and file type was incorrect.
            echo $j.
            ').<span id="error">***Invalid File Size or Type***</span><br/><br/>';
        }
    }

//End Image Upload Section

图片 所有错误的图片(4张图片中的3张上传成功后

PS 附带说明一下,是否有一种简单的方法可以遍历目录并选择其中的所有图像,然后以 HTML 格式显示它们?

标签: phphtmlmysqlimage

解决方案


推荐阅读