Skip to content
PHP Logo

How can PHP be used to automatically label or rename uploaded files based on user IDs?

When a user uploads a file, you can use PHP to automatically label or rename the file based on their user ID. This can help organize and track files based on the user who uploaded them. You can achieve this by capturing the user ID when the file is uploaded and then renaming the file using that ID before saving it to the server.

php
<?php
// Get the user ID (you can replace this with your actual user ID retrieval method)
$user_id = 123;

// Get the uploaded file name
$uploaded_file = $_FILES['file']['name'];

// Rename the file using the user ID
$new_file_name = $user_id . '_' . $uploaded_file;

// Move the uploaded file to a specific directory with the new file name
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $new_file_name);

echo "File uploaded and renamed successfully!";
?>