I have this code to validate part of a file upload:

if (!($fileExt == 'doc' || $fileExt == 'docx' || $fileExt == 'pdf')) {
$error = 'The file does not meet the file type requirments. Only Microsoft Document and PDF files are allowed.';
$etype = '1';
include ('inc/error.php');
}

Is it possible to just use an array with all the extensions and then loop through it in the IF statement? Instead of me manually having to writing out the OR statements, can I just define the array and let it loop through, no matter how many elements there are?

Dani AI

Generated

As pointed out, a whitelist is the right idea instead of long OR chains. For real-world uploads, treat the extension check as the first, fast filter and add at least a server-side MIME/magic-bytes check and other safeguards. That avoids trusting user-supplied data and handles case differences or double extensions.

A concise workflow to follow:

  • Normalize and extract the extension (use pathinfo) and check it against a maintained whitelist from configuration or a DB (use an associative lookup for speed).
  • Verify the actual file type on disk using PHP's finfo (server-side MIME detection), not $_FILES['...']['type'].
  • Confirm the upload came via HTTP POST, enforce size limits, sanitize the filename, store files outside the webroot, and move them with move_uploaded_file.

Example: normalize extension and test against a configured whitelist (store the allowed list centrally rather than hard-coding):

$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$whitelist = array_flip($config['allowed_extensions']); // config holds strings
if (!isset($whitelist[$ext])) { /* reject */ }

Example: verify server-side MIME (use keys for fast checks):

$allowedMimes = array(
  'application/pdf' => true,
  'application/msword' => true,
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => true
);
$f = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f, $tmpPath);
finfo_close($f);
if (!isset($allowedMimes[$mime])) { /* reject */ }

References and further reading: PHP pathinfo and finfo_file documentation for safe handling (pathinfo, finfo_file), and the OWASP File Upload Cheat Sheet for hardening production handling (OWASP File Upload Cheat Sheet). This complements ’s whitelist suggestion and fills gaps around security and robustness.

Recommended Answers

All 2 Replies

You don't need a loop.

if (!in_array($fileExt, array('doc', 'docx', 'pdf'))) {
// your stuff

Just what I need, thanks very much! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.