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!