简体   繁体   中英

How to php upload a image with a predefined custom name/

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM