What is the purpose of the $_FILES[] array in PHP and how is it used for file uploads?
The $_FILES[] array in PHP is used to handle file uploads from HTML forms. It allows you to access information about the uploaded file such as its name, type, size, and temporary location on the server. By using this array, you can move the uploaded file to a permanent location on the server or perform any necessary validations on the file before processing it further.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
Keywords
Related Questions
- What steps should be taken to troubleshoot template functionality in a PHP CRM system?
- How can the code be modified to allow registered users to download files from a specific directory on the web server?
- What are some common pitfalls to avoid when using SimpleXML and XPath in PHP for XML data manipulation?