PHP Image Upload Example

Apr 07, 2021 . Admin

Hi Guys,

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

PHP Image Upload

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

PHP Image 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['img'])) {
        $file_name = $_FILES['img']['name'];
        $file_size = $_FILES['img']['size'];
        $file_tmp = $_FILES['img']['tmp_name'];
        $file_type = $_FILES['img']['type'];

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

?>

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

PHP Image Upload Example

<?php echo $msg; ?>
</body> </html>

It will help you..

#PHP