PHP 8: Modern PHP Development · Security for PHP Applications

File Uploads, Input Hardening and Secrets

Handle uploads safely and keep credentials out of code.

For uploads: check $_FILES['f']['error'], enforce size limits (upload_max_filesize, post_max_size and in code), detect the real MIME type with finfo, generate your own filename, store outside the web root or in object storage, and never execute uploaded files. Keep secrets (DB passwords, API keys) in environment variables or a secret manager, not in the repository; rotate any secret that leaks. Keep PHP and Composer dependencies patched (composer audit).

<?php
$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    throw new UploadFailed('No file uploaded');
}
if ($file['size'] > 2 * 1024 * 1024) {
    throw new UploadFailed('Max 2 MB');
}
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
$ext = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'][$mime] ?? null;
if ($ext === null) {
    throw new UploadFailed('Only JPEG, PNG or WebP');
}
$name = bin2hex(random_bytes(16)) . ".{$ext}";
move_uploaded_file($file['tmp_name'], "/var/app/storage/avatars/{$name}");

Common pitfalls

  • Trusting the client-provided filename or MIME type.
  • Saving uploads in a web-accessible directory where .php files could execute.
  • Committing .env files with real credentials.

Key points

  • Validate size and real MIME type
  • Generate filenames; store outside web root
  • Secrets in environment/secret managers

Further reading: OWASP File Upload Cheat Sheet

Practice questions

Why generate your own filename for uploads?

Answer

User-supplied names can contain path traversal (../), dangerous extensions (.php), or collisions. Random names with an extension derived from the verified MIME type are safe.

What should you do if an API key is accidentally committed?

Answer

Revoke/rotate it immediately (history keeps it even after deletion), then remove it from the repo, and add secret scanning to prevent recurrence.

Open in the app to mark lessons complete, take notes and track your progress.