Let me explain what i am hope to acomplish:

I want to allow my users to upload a image as avatar.

I found many php upload tutorials but i don't know hoy to upload the avatars as user_id.ext in /avatars folder.

I hope i was clear, thanks.

有帮助吗?

解决方案

In any upload script, you go through a few basic steps. First, you get data from $_FILES telling you where the temporary upload file is. You validate the file based on something to make sure it's not evil/malicious/wrong. Then you rename it and move it somewhere useful. In your last step, when you move the image to where it's going, take that opportunity to name the file as you like. If you're dealing with a user's account it should be trivial to get the username, id, middle name, etc and use that to set the file's name.

其他提示

This script gets the uploaded file and save it as /avatars/$user_id.ext, $user_id retrieved from POST:

<?php
if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
    move_uploaded_file($_FILES["file"]["tmp_name"], "/avatar/{$_POST['user_id']}.ext");
    echo "Stored in: " . "/avatar/{$_POST['user_id']}.ext";

}    
?>

And this is the form:

<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="user_id" value="<?php echo $user_id ?>">
<input type="submit" value="submit"></form>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top