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:
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!