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
Release: 2024-11-29 22:36:10
Original
637 people have browsed it

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.";
    }
}
Copy after login

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">
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template