How can a PHP beginner ensure the security and functionality of a file upload script, especially when unfamiliar with PHP coding practices?
To ensure the security and functionality of a file upload script as a PHP beginner, you can use built-in PHP functions like `move_uploaded_file()` to securely handle file uploads and check the file type and size before processing it. Additionally, sanitize user input to prevent injection attacks and use proper error handling to catch any issues that may arise during the upload process.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
// Check file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowedTypes)) {
die('Unsupported file type.');
}
// Check file size
if ($file['size'] > 5242880) { // 5MB limit
die('File size is too large.');
}
// Move uploaded file to desired directory
$uploadDir = 'uploads/';
$uploadPath = $uploadDir . basename($file['name']);
if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}
} else {
echo 'No file uploaded.';
}
}
?>
Related Questions
- What common mistakes do PHP beginners make when transferring their website from local to a hosting provider like Strato?
- How can you display the approximate remaining runtime of a PHP script with multiple cURL requests on the screen?
- What are common pitfalls when inserting data from a PHP form into a MySQL database?