Jump to content

Image Uploading


White_Lily

Recommended Posts

Okay, I want to be able to have people upload an avatar/banner image, it needs to be done so that when they click the file and hit upload, the script takes the file name, seperates it from the file extension, renames the file with a uniqueID, and then adds the file extension back on to give the file its new name, and then move it to a more permanent location on the server...

 

I am basically asking how I go about doing this?

Link to comment
https://forums.phpfreaks.com/topic/269858-image-uploading/
Share on other sites

You start off first by creating the font - end. You need upload and submit buttons in a form element where it will send the data with POST:

Save this as upload_avatar.html

<form action="upload_avatar_process.php" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" id="avatar" />
<br />
<input type="submit" value="Upload your avatar" />
</form>

 

Then you need to create a separate page, upload_avatar_process.php where you have to

 

1. Check whether the user has basically uploaded the file;

 

2. Disallow unwanted extensions;

 

3. Set a file size's limit;

 

4. Move the image from its temporary location to a directory of your choice

 

 

Here is the code:

 

if(isset($_FILES['avatar'])){
$allowed_extensions = array('jpeg','jpg','png','gif');
$file_name = htmlentities($_FILES['avatar']['name']);
$file_extension = strtolower(end(explode('.',$_FILES['avatar']['name'])));
$file_location = $_FILES['avatar']['tmp_name'];
$file_size = $_FILES['avatar']['size'];
if(!in_array($file_extension, $allowed_extensions)){
$errors[] = 'File has an invalid extention. Allowed extensions are jpg, jpeg, png and gif';

}
if($file_size > 133120){
$errors[] = 'File is way too large. Max size is 130 KiB';

}
if(!empty($errors)){
foreach($errors as $error){
echo $error.'<br />';

}

}if(empty($errors)){
move_uploaded_file($file_location, 'avatars/'.$file_name);
}


}

 

 

Note that the $_FILES array is multidimensional, that's why you need to refer to its values with double brackets like this:

 

$_FILES['avatar']['name']; 

Link to comment
https://forums.phpfreaks.com/topic/269858-image-uploading/#findComment-1387463
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.