What is the usage of the PHP $_FILES function?

$_FILES is a superglobal variable in PHP used to handle files uploaded via the POST method. It contains an associative array with information about the uploaded file, such as the file name, file type, and the temporary file path. Using $_FILES makes it easy to access information about uploaded files and make the necessary adjustments.

The basic steps for using $_FILES are as follows:

  1. Use the input tag in HTML forms and set the type attribute to file to specify the form field for file upload.
  2. In a PHP script, information about an uploaded file can be obtained through the $_FILES superglobal variable.
  3. Process uploaded files, such as moving them to a specified directory or renaming them.

For example, here is a simple code example for uploading files:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传文件">
</form>
<?php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo '文件上传成功!';
    } else {
        echo '文件上传失败!';
    }
}
?>

In the example above, once the user uploads a file, the PHP script will move the file to the designated ‘uploads’ directory and display a corresponding message. Using the $_FILES variable, we can easily manage user-uploaded files.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds