Home >Backend Development >PHP Tutorial >How to Solve File Upload Issues in PHP Using $_FILES?

How to Solve File Upload Issues in PHP Using $_FILES?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 22:36:10714browse

How to Solve File Upload Issues in PHP Using $_FILES?

File Uploading with PHP

This guide demonstrates how to upload files in PHP, addressing a common error encountered in previous approaches.

Problem:

When attempting to upload a file to a specified folder, an error arises due to the use of the deprecated HTTP_POST_FILES variable.

Solution:

The following PHP code provides a modernized and updated solution for file uploading:

$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowedTypes = ['jpg', 'png'];

if (isset($_POST["submit"])) {
    // Check file type
    if (!in_array($imageFileType, $allowedTypes)) {
        $msg = "Type is not allowed";
    }
    // Check if file already exists
    elseif (file_exists($target_file)) {
        $msg = "Sorry, file already exists.";
    }
    // Check file size
    elseif ($_FILES["fileToUpload"]["size"] > 5000000) {
        $msg = "Sorry, your file is too large.";
    }
    elseif (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    }
}

Explanation:

  • $_FILES["fileToUpload"] retrieves the file upload information.
  • $target_dir specifies the destination folder.
  • Conditional statements check file type, existence, and size.
  • move_uploaded_file() moves the file to the specified location.
  • The $msg variable stores messages based on the upload status.

HTML Code for Uploading:

<form action="upload.php" method="post">

Using this updated code, you can successfully upload files to your desired folder and handle validation errors appropriately.

The above is the detailed content of How to Solve File Upload Issues in PHP Using $_FILES?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn