Skip to content
PHP Logo

What security considerations should be taken into account when allowing users to upload files in PHP?

When allowing users to upload files in PHP, it is crucial to validate the file type, limit the file size, and store the files in a secure directory outside of the web root to prevent direct access. Additionally, consider renaming the uploaded files to prevent malicious scripts from being executed on the server.

php
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type.');
}

// Limit file size
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
    die('File is too large.');
}

// Store file in a secure directory
$uploadDir = '/path/to/secure/directory/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);

// Rename uploaded file
$newFileName = uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $newFileName);