Home  >  Article  >  Backend Development  >  How to Move Files to Different Server Folders in PHP?

How to Move Files to Different Server Folders in PHP?

DDD
DDDOriginal
2024-11-02 03:32:30429browse

How to Move Files to Different Server Folders in PHP?

Moving a File to a Different Server Folder in PHP

Users often need the ability to manage uploaded files, including removing unwanted ones. While the unlink function was previously used for this purpose, concerns about security risks have led to the recommendation of using alternative methods.

To move a file to a different folder on the server while preserving its accessibility to users, the rename function can be employed. It allows for the seamless movement of files without deletion. For instance, to move user/image1.jpg to user/del/image1.jpg, the following code can be used:

rename('image1.jpg', 'del/image1.jpg');

If the original file needs to be retained in its current location, the copy function is a viable option:

copy('image1.jpg', 'del/image1.jpg');

For files that were uploaded through the POST request, the move_uploaded_file function is specifically designed and highly recommended:

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

The above is the detailed content of How to Move Files to Different Server Folders in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn