Home >Backend Development >PHP Tutorial >Why Am I Getting the \'Undefined variable: HTTP_POST_FILES\' Error When Uploading Files in PHP?

Why Am I Getting the \'Undefined variable: HTTP_POST_FILES\' Error When Uploading Files in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 01:57:09380browse

Why Am I Getting the

Upload a File Using PHP: Troubleshooting "Undefined Variable: HTTP_POST_FILES" Error

Uploading files to a server using PHP can be a simple process. However, it's essential to address any errors that may arise during the process.

Problem:
An error occurs when attempting to upload a file using PHP: "Notice: Undefined variable: HTTP_POST_FILES".

Cause:
The $HTTP_POST_FILES variable refers to the global array that stores uploaded file information. However, it has been deprecated since PHP 4.1.0 and is not recommended for use.

Solution:
Modern PHP versions expect a different structure for accessing uploaded file data. Instead of $HTTP_POST_FILES, use the following methodology:

$_FILES["file_name"]["key"]

Where:

  • file_name is the name of the input field where the file was selected.
  • key is the specific aspect of the file being accessed (e.g., "name", "type", "size", "tmp_name").

Example Code:

The following improved PHP code adheres to best practices for file uploading:

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

if (isset($_POST["submit"])) {
    // Check file type
    if (!in_array($imageFileType, $allowedTypes)) {
        echo "Type is not allowed";
    }
    // Check if file already exists
    elseif (file_exists($target_file)) {
        echo "Sorry, file already exists.";
    }
    // Check file size
    elseif ($_FILES["filename"]["size"] > 5000000) {
        echo "Sorry, file is too large.";
    } else {
        // Upload file
        if (move_uploaded_file($_FILES["filename"]["tmp_name"], $target_file)) {
            echo "File uploaded successfully.";
        }
    }
}

The above is the detailed content of Why Am I Getting the \'Undefined variable: HTTP_POST_FILES\' Error When Uploading Files in PHP?. 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