PHP $_FILES Variable – A Beginner Guide

By | September 14, 2020

PHP $_FILES variable is often used when uploading files. In this tutorial, we will introduce it for php beginners.

What is $_FILES?

$_FILES contains some information on uploaded files, such as file name, file size, file type etc. We can use these information to save files.

How to get file information from $_FILES?

Look at code below:

    <form action="upload-manager.php" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
    </form>

We can use $_FILES[‘photo’] to get file information, where photo is the name of the file.

php $_FILES variable

What information we can get from php $_FILES?

As to example above, we can use $_FILES[‘photo’] to get these information:

$_FILES[‘photo’][‘name’] file name testfile.txt
$_FILES[‘photo’][‘type’] file mime type application/octet-stream, image/gif
$_FILES[‘photo’][‘size’] file size in byte 4321
$_FILES[‘photo’][‘tmp_name’] the path of file that is saved in server temporarily, this value can be set by upload_tmp_dir in php.ini such as: /tmp/php6wHXmC
$_FILES[‘photo’][‘error’] the error code
UPLOAD_ERR_OK (0) upload successfully
UPLOAD_ERR_INI_SIZE (1) the file size if bigger than upload_max_filesize in php.ini
UPLOAD_ERR_FORM_SIZE (2) the file size is larger than maximum size in html form
UPLOAD_ERR_PARTIAL (3) a part of file has been uploaded
UPLOAD_ERR_NO_FILE (4) no file uploaded
Category: PHP

Leave a Reply

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