PHP File Upload Example

Apr 06, 2021 . Admin

Hi Guys,

In this blog, I’ll explain the basics of file upload in PHP.

PHP File Upload

PHP sanctions you to upload single and multiple files through few lines of code only.

PHP file upload features sanctions you to upload binary and text files both. Moreover, you can have the full control over the file to be uploaded through PHP authentication and file operation functions.

PHP $_FILES

The PHP global $_FILES contains all the information of file. By the avail of $_FILES global, we can get file denomination, file type, file size, temp file name and errors associated with file.

Here, we are surmising that file denomination is filename.

$_FILES['filename']['name']

Here, we return the file name

$_FILES['filename']['type']

returns MIME type of the file.

$_FILES['filename']['size']

returns size of the file (in bytes).

$_FILES['filename']['tmp_name']

returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']

returns error code associated with this file.

move_uploaded_file()

The move_uploaded_file() function moves the uploaded file to an incipient location. The move_uploaded_file() function checks internally if the file is uploaded exhaustive the POST request. It moves the file if it is uploaded through the POST request.

Syntax
bool move_uploaded_file ( string $filename , string $destination );  
Example

<?php

    if (isset($_FILES['file'])) {
        $file_name = $_FILES['file']['name'];
        $file_size = $_FILES['file']['size'];
        $file_tmp = $_FILES['file']['tmp_name'];
        $file_type = $_FILES['file']['type'];

        $target_path = "fileupload/";  
        $target_path = $target_path.basename($file_name);   
          
        if(move_uploaded_file($file_tmp, $target_path)) {  
            $msg = "File uploaded successfully!";  
        } else{  
            $msg = "Sorry, file not uploaded, please try again!";  
        } 
    }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    PHP File Upload Example - MyWebtuts.com
    
    
    
    
    
</head>
<body>

<?php echo $msg; ?>
<script> $(".custom-file-input").on("change", function() { var fileName = $(this).val().split("\\").pop(); $(this).siblings(".custom-file-label").addClass("selected").html(fileName); }); </script> </body> </html>

It will help you..

#PHP