How to Move Files to Different Server Folders in PHP?

DDD
Release: 2024-11-02 03:32:30
Original
493 people have browsed it

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');
Copy after login

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');
Copy after login

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");
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template