Helper class for uploading files

Hey guys! This week I added a class to my GitHub account that I implemented to help with the file upload process. It is a very interesting helper, because it is easy to use and you can define several rules such as file size limit, extension filter, overwriting files, etc.

To download the class, you can access http://www.github.com/rafaelwendel/UploadHelper or through your command line.

$ git clone https://github.com/rafaelwendel/UploadHelper.git

To use the class is easy, just include the path and create an instance

1
2
3
<?php
   include ('UploadHelper.php');
   $upload = new Upload_Helper();

To upload, define a file.

3
4
5
//After a form submit
$file = $_FILES['file'];
$upload->set_file($file);

Define the directory where the file should be sent

5
$upload->set_uploads_folder('path/to/uploads/folder');

Define valid extensions

6
7
$allowed = array('jpg', 'png', 'gif', 'bmp'); //images only
$upload->set_allowed_exts($allowed);

Do you want to rename the file? (By default, it keeps the same name)

7
$upload->set_file_name('new_name'); //O novo nome do arquivo

Do you want to overwrite the file with the same name, if any? ( True is the default)

8
$upload->set_overwrite(false); // Do not overwrite files with the same name

What is the file size limit? (2MB is the default)

9
$upload->set_max_size(5); //Set the file size in MegaBytes (MB)

After everything is defined, upload it.

10
11
12
13
14
15
if($upload->upload_file()){
    echo 'File uploaded successfully. Path: ' . $upload->get_file_path(); 
}
else{
    echo $upload->get_error();
}

By default, the error messages are in English (en), but if you want to change to Portuguese it is easy.

5
$upload->set_language('pt'); //Sets the language for error messages

And ready! Very easy to use and I hope it helps you.

Hugs!

Holds a university degree in Information Systems, a postgraduate degree in Database Systems and a master's degree in Education with a focus on Sociocommunity Technologies. He works as a professor of technical and technological education at the Federal Institute of Education, Science and Technology of São Paulo, teaching subjects in the areas of programming, database, project development and software engineering.

Posts relacionados

Leave a Reply

Your email address will not be published. Required fields are marked *