繁体   English   中英

如何在将上传文件保存到PHP目录之前重命名?

[英]How to rename uploaded file before saving it into a directory in PHP?

我使用这个简单的上传和调整PHP项目的图像来完成我的项目。 https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416但我不知道如何在上传后重命名文件。 我想重命名文件并将其上传到服务器以及数据库中。 以下是代码:

public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}

我使用了很多方法,例如basename它不能对它,任何想法? 谢谢

而不是使用move_uploaded_file根据下面给出的代码示例使用它。

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

你可以这样做

public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {

              $tempName = explode(".", $this->files['name'][$i]);
              $newName = "IMAGE_NAME"; //generate unique string to avoid conflict
              $newfilename = $newName . '.' . end($tempName );
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$newfilename) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}

$newName您可以为您的文件生成新名称。

更新

为避免冲突,每次生成名称时都使用唯一字符串。

这是你的解决方案

public function run(){
    $total = count($this->files);
    for($i=0; $i<$total; $i++){
        if(empty($this->files['name'][$i]) === false){
            $ext = substr(strtolower(strrchr($this->files['name'][$i], '.')), 1); //get the extension
            $new_name = 'new-name'.date('dmY').$ext;
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$new_name) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }
    return empty($this->errors);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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