StackExchange
5
votes
9087654 modified 1 hour ago

2 Answers

by SecurityPro • 20 minutes ago

Use secure practices when handling file uploads to prevent malicious activities such as file system manipulation or malicious code execution. Follow these steps:

  1. Validate uploaded files using $_FILES['userfile']['type'] to ensure they are of a safe type.
  2. Sanitize the file name and store files in a non-public directory.
  3. Generate a unique name using bin2hex(random_bytes(16)).
  4. Limit access so that users can only see their own files.

Here's an example code snippet:

$filename = bin2hex(random_bytes(16)) . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$directory = 'uploads/';
$upload = ($directory . $filename);
move_uploaded_file($_FILES['file']['tmp_name'], $upload);
by DevCode • 15 minutes ago

You should also consider:

  • Implementing a virus scanning service such as ClamAV before saving.
  • Limiting file upload sizes and types.
  • Using a WAF or similar technology to detect suspicious patterns.

Here’s an example of how you should do it:


// Example PHP Upload Code
$allowed_mime_types = ['image/png', 'image/jpeg'];
if (!in_array($_FILES['file']['type'], $allowed_mime_types)) {
    die("Invalid filetype.");
}

Your Answer