Search

Beginner's Guide to File Uploads in PHP

3 min read
2 views

In this tutorial, we'll explore how to implement file uploads in Setting Up the HTML Form

To start, create an HTML form that allows users to select and submit files. Use the <form> tag with the enctype attribute set to "multipart/form-data". This encoding type is necessary for file uploads.

Prompt
<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="fileUpload" /> <input type="submit" value="Upload" /> </form>

$_FILES superglobal array to access information about the uploaded file.

Prompt
<?php $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["fileUpload"]["name"]); $uploadSuccess = move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $targetFile); if ($uploadSuccess) { echo "File uploaded successfully."; } else { echo "File upload failed."; } ?>

Validating File Types and Sizes

To enhance security, we can add validation to ensure that only certain file types and sizes are allowed.

Prompt
$allowedTypes = array("jpg", "png", "gif"); $maxSize = 2 * 1024 * 1024; // 2MB $fileExtension = strtolower(pathinfo($_FILES["fileUpload"]["name"], PATHINFO_EXTENSION)); if (!in_array($fileExtension, $allowedTypes)) { echo "Only JPG, PNG, and GIF files are allowed."; } elseif ($_FILES["fileUpload"]["size"] > $maxSize) { echo "File size exceeds the limit."; } else { // Perform the file upload }

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!