francoleung
francoleung

Reputation: 257

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

I use this Simple upload and resize image on PHP project to do my project. https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416 but I don't know how to rename the file after upload. I want to rename file and upload it into server as well as in database. The follow is code:

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

I use a lot of method , eg basename It can't to it, any idea?? Thanks

Upvotes: 1

Views: 207

Answers (3)

Regolith
Regolith

Reputation: 2971

You can do this

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

In $newName you can generate new name for your file.

Update

To avoid conflict use unique string each time when you generate the name.

Upvotes: 1

Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

Here is your solution

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

Upvotes: 1

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Instead of using move_uploaded_file use it as per code example given below.

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

Upvotes: 1

Related Questions