File extension verification is crucial when handling file uploads in PHP. One common method involves using the pathinfo function, as demonstrated in the query:
$filename = $_FILES['video_file']['name']; $ext = pathinfo($filename, PATHINFO_EXTENSION); if ($ext !== 'gif' || $ext !== 'png' || $ext !== 'jpg') { echo 'error'; }
However, this approach may not be optimal when supporting a wider range of extensions. Consider the case where you allow 20 different extensions:
if ($ext !== 'gif' || $ext !== 'png' || $ext !== 'jpg' || ...) { // ... }
Such code would be verbose and potentially inefficient. An alternative method involves utilizing an array of allowed extensions:
$allowed = array('gif', 'png', 'jpg'); $filename = $_FILES['video_file']['name']; $ext = pathinfo($filename, PATHINFO_EXTENSION); if (!in_array($ext, $allowed)) { echo 'error'; }
This approach simplifies the code and improves efficiency by reducing the number of comparisons required. By checking if the extension exists in the $allowed array, you can quickly validate its validity.
The above is the detailed content of How Can I Efficiently Validate File Extensions in PHP?. For more information, please follow other related articles on the PHP Chinese website!