PHP Upload File

Keywords: PHP

PHP scripts can be used with HTML forms to allow users to upload files to the server. Files are initially uploaded to temporary directories, and then relocated to the target through PHP scripts. The upload_tmp_dir information in the phpinfo.php page will be used for temporary directories for file uploads, and the maximum allowable size of upload_max_filesize can be expressed as upload_max_filesize. These parameters are set in the PHP configuration file php.ini.

The process of uploading files follows the following steps
The following HTM code creates an uploader form. This form sets the method property to post and the enctype property to multipart/form-data
<?php
if(isset($_FILES['image'])){
        $errors= array();
        $file_name = $_FILES['image']['name'];
        $file_size = $_FILES['image']['size'];
        $file_tmp = $_FILES['image']['tmp_name'];
        $file_type = $_FILES['image']['type'];
        $name_arr = explode('.',$_FILES['image']['name']);
        $file_ext=strtolower(end($name_arr));
        $extensions= array("jpeg","jpg","png");
        /* Expanded Name Documents Provisional for Uploading */
        if(in_array($file_ext,$extensions)=== false){
                $errors[]="Extensions are not allowed, please select one jpeg or png Papers.";
        }
        /* Specify the size of files that can be uploaded */
        if($file_size > 2097152) {
                $errors[]='File size must not exceed 2 MB';
        }
        if(empty($errors)==true) {
            /* Move the picture from the file in the temporary folder to the directory where the current script is located */
                move_uploaded_file($file_tmp,"./".$file_name);
                echo "Upload successfully";
        }else{
                print_r($errors);
        }
}
?>
<html>
<body>
<!-- action Default to current script -->
<form action = "" method = "POST" enctype = "multipart/form-data">
    <input type = "file" name = "image" />
    <input type = "submit" name="Submission" />
    <ul>
        <li>file name: <?php echo isset($_FILES['image']['name']) ? $_FILES['image']['name'] : '' ;  ?>
        <li>file size: <?php echo isset($_FILES['image']['size']) ? $_FILES['image']['size'] : '' ;   ?>
        <li>file type: <?php echo isset($_FILES['image']['type']) ? $_FILES['image']['type'] : '' ; ?>
    </ul>
</form>
</body>
</html>

  View the effect of the display

Posted by zggtf211 on Tue, 01 Oct 2019 12:06:04 -0700