我如何上传img []并在保存时重命名?

时间:2017-10-06 06:27:56

标签: php

我使用w3school示例

1)当我添加img时如何重命名,因为我想添加同名的同名图像我要重命名?

2)如果我的fileToupload[]如何上传使用for(i=0 ,i< ? ,i++)

我应该使用count($_FILES)吗?

这是我的代码:

$target_dir = "../../_files/images/source/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = md5($_FILES['fileToUpload']['tmp_name']);

// 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;
    }
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
         var_dump($_FILES["fileToUpload"]["tmp_name"], $target_file);
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

1 个答案:

答案 0 :(得分:0)

每次只更新$ target_file的值,它会自动重命名图像名称。