简体   繁体   中英

PHP - move_uploaded_file not working to copy file in same folder

Having some trouble with rewriting a photo file. I need the file name to get rewritten as a random string. The file uploads fine - I can't seem to get it copy the file and rewrite the file name to the random string. The file is going to stay in the directory.

The function is working fine and I can rewrite file name in the database, but it will not rewrite the actual file in the folder. The folder permissions are rwxr-xr-x (755).

Any thoughts?

function AfterUpdate(){
    $file = $this->file_attachment;
    $path_parts = pathinfo($file);
    $newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];

    $file_src = $_SERVER['DOCUMENT_ROOT'] . $file; 
    $newfile_src = $_SERVER['DOCUMENT_ROOT'] . $newFilename; 
    if (move_uploaded_file($file_src, $newfile_src)){
        $this->file_attachment = $newFilename;
    }
}

$newFilename contains a path location I guess by looking at the $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension']; $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension']; .

$newFilename should just be the new file name with extension. move_uploaded_file will only move files from one folder to another or the same, that already exists. But will not create a folder for you.

Simple fix. Replace move_uploaded_file with rename . The file will not be moved, just renamed.

    $file = $this->file_attachment;
    $path_parts = pathinfo($file);
    $newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];

    $file_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $file; 
    $newfile_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $newFilename; 
    if (rename($file_src, $newfile_src)){
        $this->file_attachment = $newFilename;
    }

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