Far more elegant and consistent than its native counterparts in PHP, Laravel's file manipulation functions make it easier to write the web and console applications that deal with the uploads along with the filesystem.
The following functions will make it easier for you to deal with file uploads in your application:
This function creates a form to send files (by adding
enctype='multipart/form-data'
to the<form>
element):Form::open(array('files' => true))
This function creates a file upload field:
Form::file('avatar');
This function retrieves the uploaded file and saves it to an existing folder inside
app/storage/
:$avatar = Input::file('avatars')->move(storage_path() . "/uploads/avatars");
This function retrieves the path of the uploaded file:
$path = Input::file('avatar')->getRealPath();
This function retrieves the original name of an uploaded file:
$name = Input::file('avatar')->getClientOriginalName();
This function retrieves the extension of the uploaded file:
$extension = Input::file('avatar')->getClientOriginalExtension();
This function retrieves the size of an uploaded file:
$size = Input::file('photo')->getSize();
The File
class also exposes several methods to retrieve and manipulate files:
The following methods check for the existence or type:
File::exists('path/to/file/or/directory'); File::isDirectory('path/to/directory'); File::isWritable('path/to/directory'); File::isFile('path/to/file');
This method gets the contents of a file:
File::get('path/to/file');
This method creates a file and writes to it (if the file exists, it is overwritten):
File::put('path/to/file', 'contents');
The following methods append or prepend to a file:
File::append('path/to/file', contents'); File::prepend('path/to/file', contents');
File::delete('path/to/file');
The following methods move or copy files:
File::move('path/to/file', 'new/path/to/file'); File::copy('path/to/file', 'path/to/file-copy');
The following methods help you get the basic information about a file:
File::extension('path/to/file'); File::type('path/to/file'); File::size('path/to/file'); File::lastModified('path/to/file');
This method gets an array of all the subdirectories within a given directory:
File::directories('path/to/directory');
This method gets an array of all the files in a directory:
File::files('path/to/directory');
This method recursively lists all of the files in a directory and its subdirectories:
File::allFiles('directory');
These methods perform common operations on directories:
File::makeDirectory('path/to/new/directory', $mode, $recursive); File::copyDirectory('source', 'destination', $options = null); File::deleteDirectory('path/to/directory');
This method empties a directory but does not delete it:
File::cleanDirectory('path/to/directory');